简体   繁体   English

TextWriter没有写入磁盘,没有错误

[英]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中获取行并将其写到磁盘上:

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 ? 您是否考虑过使用File.WriteAllLines http://msdn.microsoft.com/en-us/library/dd383693.aspx . http://msdn.microsoft.com/zh-CN/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. 我认为你i没有增加。 Do i++ inside the loop. 我是否在循环内i++ Also do this. 也这样做。 foreach line, write line, outside the loop flush. foreach行,写行,循环外刷新。 also remove the removeat 也删除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 谢谢你们的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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