简体   繁体   中英

TextWriter is not writing to disk, with no error

I have the following snippet of code, which takes lines from a List and writes them off to disk:

List<string> messages; // a list full of lines of text to write to file
using (System.IO.TextWriter writer = new System.IO.StreamWriter(stSessionStatusFile, true))
{
   int i = 0;
   while (i < messages.Count)
   {
      string line = messages[0];
      writer.WriteLine(line);
      writer.Flush();
      messages.RemoveAt(0);
   }
}

However... the resulting file is not created on disk, nor are there any exceptions thrown. It's like the text to write to disk just disappears into thin air. This code works in another assembly, just not in the service that I ported it to. I have no idea why the text wouldn't be written to disk in this case, many thanks for any help with solving this problem.

Have you considered using File.WriteAllLines ? http://msdn.microsoft.com/en-us/library/dd383693.aspx . My experience it's much cleaner for these types of operations. Helps narrow down the potential for errors.

I think your i is not incrementing. Do i++ inside the loop. Also do this. foreach line, write line, outside the loop flush. also remove the removeat

foreach(string line in messages) {
  writer.WriteLine(line)
}

writer.Flush();

检查您用来运行该服务的凭据...也许您可以尝试写入一些临时文件夹(例如C:\\ Temp),然后查看它是否有效

I rebooted and everything started working as expected. I don't really have an explanation as to what happened, but I'd guess that my PC is the issue here, not coder error. Thanks for the help guys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM