locked
write to txt RRS feed

  • Question

  • User-974983964 posted
    //write filename to txt
                FileStream fs = new FileStream(newPath + "\\FileInfo.txt", FileMode.OpenOrCreate);
    
                StreamWriter sw = new StreamWriter(fs);
    
                sw.WriteLine(txt.ToString());
    
                MessageBox.Show(this, "GetSuccess", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

    The MessageBox is show and when I debug txt has value.But when I open the file "FileInfo.txt" , I found it is empty?

    Wednesday, December 2, 2015 9:42 AM

Answers

  • User1724605321 posted

    Hi Melody ,

    Firstlly ,since you are writing a winform application , please post to winform forum for help .

    Secondly , you need to use  StreamWriter.Close Method () to ensure that all data is correctly written out to the underlying stream . Please try below code:

    sw.WriteLine(txt.ToString());
    sw.Close();

    Hope it helps.

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 2, 2015 9:48 AM
  • User1428246847 posted

    You will be better off using 'using'; you will run out of resources quickly if you don't cleanup after yourself ;-)

    using (FileStream fs = new FileStream(newPath + "\\FileInfo.txt", FileMode.OpenOrCreate))
    {
        using (StreamWriter sw = new StreamWriter(fs))
        {
            sw.WriteLine(txt.ToString());
        }
    }
    
    

    This will properly close and cleanup all resources that you use.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 3, 2015 5:11 AM

All replies

  • User1724605321 posted

    Hi Melody ,

    Firstlly ,since you are writing a winform application , please post to winform forum for help .

    Secondly , you need to use  StreamWriter.Close Method () to ensure that all data is correctly written out to the underlying stream . Please try below code:

    sw.WriteLine(txt.ToString());
    sw.Close();

    Hope it helps.

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 2, 2015 9:48 AM
  • User1428246847 posted

    You will be better off using 'using'; you will run out of resources quickly if you don't cleanup after yourself ;-)

    using (FileStream fs = new FileStream(newPath + "\\FileInfo.txt", FileMode.OpenOrCreate))
    {
        using (StreamWriter sw = new StreamWriter(fs))
        {
            sw.WriteLine(txt.ToString());
        }
    }
    
    

    This will properly close and cleanup all resources that you use.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 3, 2015 5:11 AM