Saving a string into a new file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mbewers1
    New Member
    • Feb 2009
    • 68

    #1

    Saving a string into a new file

    I'm writing code to perform a rather simple task but it appears to be more difficult than it should be. I have a fileContent string, containing a long string item, which I have generated within my code and wish to save and a path variable which contains the new path I wish to save the file to.

    Code:
    /*
         * Process of exporting file to save it as a single document, ensuring
         * that the correct extension is used.
         */ 
        private void ExportToSave(string path, string fileContent)
        {
            HttpResponse hr = HttpContext.Current.Response;
            hr.AddHeader("Content-Disposition", "attachment;filename=ProRefExport");
    
            StreamWriter sw = new StreamWriter(path);
            HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
            sw.WriteLine(string.Format("Generated by user on", DateTime.Today));
            sw.Close();
            htmlWriter.Close();
    
            File.WriteAllText(path, fileContent, System.Text.Encoding.ASCII);
    
            hr.ContentType = "text/html";
            hr.End();
    
            base.Render(htmlWriter);
        }
    When I debug the code, the fileContent variable contains the string in full but, once the file is downloaded and saved, however, there is no text inside it.

    I tried writing the fileContent string as an array of bytes using the same StreamReader object I created but made things worse as I had file process errors.

    Why might this be and what can I do to solve this problem?
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    Have you tried putting a breakpoint at line 7 then walk through line by line to see where you get an error?

    Line 16 is a File.Write. Have you opened the file with write privileges first someplace? I don't see that.

    Comment

    • mbewers1
      New Member
      • Feb 2009
      • 68

      #3
      Yes, I've tried debugging it and the text shows up but no file content is saved.
      I didn't realised that properties had to be assigned to a File object, I thought File.Write literally meant make a new file.

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        Title: Saving a string into a new file
        Comment: text shows up but no file content is saved.

        What does "shows up" mean? Is the text in the file? Isn't that the goal; to make a file that contains your string?

        Again I suggest that you open the file for writing before you try to write to it.
        http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx

        Comment

        Working...