open a streamwriter/reader

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • michaeldebruin
    New Member
    • Feb 2011
    • 134

    open a streamwriter/reader

    I am trying to make a program which acts just a bit like a database. The only problem yet is that I had problems with my streamwriters and readers. It seems that my streamwriter only wants to write a string in a txt file when I say
    Code:
    sw.Close();
    , but how can I open the stream again?
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    Only close the stream when you're done with it. That said, if you want to reopen it, just do it the same way you did in the first place.

    Comment

    • adriancs
      New Member
      • Apr 2011
      • 122

      #3
      Open, Read and Close a file:
      Code:
      string FileName = @"C:\myFileName.txt";
      string[] stringArray = null;
      
      if (File.Exists(FileName))
      {
          stringArray = File.ReadAllLines(FileName);
          foreach (string line in stringArray)
          {
              // Do something here...
          }
      }
      else
      {
          MessageBox.Show("File Not Exists");
      }
      Open, Write and Close a file:
      Code:
      string filePath = @"C:\";
      string fileName = "myFileName.txt";
      string[] stringArray = null; // replace this with your data
      if (Directory.Exists(filePath))
          File.WriteAllLines(filePath + fileName, stringArray, Encoding.UTF8);
      else
          MessageBox.Show("The directory is not exist");

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        If you are only seeing your data written on the .Close() then I would guess you need to call Flush().
        You should be able to keep the file open(if that is what you want) and keep writing, calling Flush() when required

        Comment

        • bvrwoo
          New Member
          • Aug 2011
          • 16

          #5
          You must keep the file open while writing because when you close all operations are processed and then the file is close and unmanaged resources are destroyed.
          Code:
          using (TextWriter tw = new StreamWriter(file))
          {
              foreach (string s in strings)
                  tw.WriteLine(s);//or whatever you are saving as string
          }
          you don't need to call on tw.Close() because it is in a 'using' block which you can use for any class/struct which inherits the IDisposable interface.

          Comment

          Working...