c# - 将文本写入文件 System.IO.IOException
问题描述
我有以下代码可以将一些当前位置写入文件:
while (onvifPTZ != null)
{
string[] lines = {"\t Act Value [" + curPan.ToString() +
"," + curTilt.ToString() +
"," + curZoom.ToString() + "]","\t Ref Value [" + newPTZRef.pan.ToString() +
"," + newPTZRef.tilt.ToString() +
"," + newPTZRef.zoom.ToString() + "]", "\t Dif Value [" + dPan.ToString() +
"," + dTilt.ToString() +
"," + dZoom.ToString() + "]" + Environment.NewLine };
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(mydocpath, "WriteLines1.txt")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
}
我有一个错误告诉我该进程无法使用位于(路径..)的文件,因为它已在使用中。我尝试重新启动并删除文件(它实际上工作了一次)但似乎没有任何工作。我可以用不同的方式编写它以使其正常工作,并且每次启动它都会创建一个新文件吗?
另一个问题是,如果有人知道为什么它只保存一个位置......该位置每隔几毫秒更新一次,我想要该文件中的每个位置,而不仅仅是一个......我应该怎么做?
同样的事情在控制台中完美运行,每次也给出新位置,但不在文件中。
解决方案
您应该调用 StreamWriter.Flush() 或设置 StreamWriter.AutoFlush = true
另外,在写入之前或之后,我通常会检查文件是否被另一个进程锁定:
bool b = false;
while(!b)
{
b = IsFileReady(fileName)
}
...
/// <summary>
/// Checks if a file is ready
/// </summary>
/// <param name="sFilename"></param>
/// <returns></returns>
public static bool IsFileReady(string sFilename)
{
// If the file can be opened for exclusive access it means that the file
// is no longer locked by another process.
try
{
using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
{
return inputStream.Length > 0;
}
}
catch (Exception)
{
return false;
}
}
推荐阅读
- r - 我在 R 上有 2 个图表。它们有不同的 x 轴,但趋势图相似。我如何将它们覆盖在 r 上?
- java - 使用 Java 从 Google 请求 OAUTH 的 JWT 签名无效
- javascript - React.js 奇怪的行为
- r - 反向术语文档的组变量
- javascript - TypeORM 中的 FILTER 语句
- javascript - ASP.Net 验证器成功时如何调用 JavaScript 函数?
- python - python学习tkinter listbox catch no selection错误
- java - 服务器突然发送 Fin Push Ack
- java - 如何在带有 MangoDB 的 Spring Boot 中使用聚合和标准获取包含字段计数的数据列表
- css - Django #hashtags 在 url