0

I'm having trouble with coppying an array of strings to a new text file, When I create a new file,The file was created,but when I try to copy the array to the new text file,the file stays empty no matter what I tried.

I tried to use "using" to create the file,I have also tried to create a new text file without "using" and made sure not to forget to use "file.Close();" ,nothing seems to work.

any suggestions?

Jonathan.

this is my corrent code (the problem is located only after the "for" loop):

static void Main(string[] args) {
    string fileContent = File.ReadAllText("FreeText.txt");
    string[] chars = fileContent.Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

    for(int i =0;i<chars.Length;i++) {
        if (i % 2 != 0)
            chars[i] = chars[i].ToUpper();
        else
            chars[i] = chars[i].ToLower();
    }

    using( FileStream fs = new FileStream(@"C:\Users\Yonatan\Documents\Visual Studio 2013\Projects\Clab2\Clab2\bin\Debug\Test.txt",
    FileMode.OpenOrCreate,
    FileAccess.Write)) {
        StreamWriter writer = new StreamWriter(fs);
        writer.WriteLine(chars);
        fs.Flush();
    }
}
J.Cohen
  • 3
  • 7
  • If the `strings` in the new files are in the `chars`, then should you not the `chars` line by line to your new file? – Ian Mar 12 '16 at 10:08
  • Yes sorry,I tried to copy some random text also.I will edit it. – J.Cohen Mar 12 '16 at 10:10

2 Answers2

0

use StreamWriter directly from file path

class Program
{
    static void Main()
    {
       // Write single line to new file.
       using (StreamWriter writer = new StreamWriter("C:\\log.txt", true))
       {
          writer.WriteLine("Important data line 1");
       }

       // Append line to the file.
       using (StreamWriter writer = new StreamWriter("C:\\log.txt", true))
       {
           writer.WriteLine("Line 2");
       }
    }
}
MSH
  • 193
  • 2
  • 16
0

The code you need is in the answer here: How to write data to a text file in C#?

I've included a solution anyhow:

   using( FileStream fs = new FileStream(@"C:\Test.txt",
                      FileMode.OpenOrCreate,
                      FileAccess.Write))
   {
       StreamWriter writer = new StreamWriter(fs);
       byte[] info = new UTF8Encoding(true).GetBytes(fileContent);
       fs.Write(info, 0, info.Length);
       fs.Close();
   } 
Community
  • 1
  • 1
Davy C
  • 639
  • 5
  • 16