我有以下代码将一些当前位置写入文件:
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);
}
}
我有一个错误告诉我该进程无法使用File at(path ..),因为该文件已在使用中。我尝试重新启动,然后删除File(它实际上工作了一次),但似乎没有任何作用。我可以写不同的方式使其起作用,并且每次启动它都会创建一个新文件吗?
另一个问题是,如果有人知道为什么它只保存一个职位...该职位每几毫秒更新一次,我想要该文件中的每个职位,而不只是一个..我应该怎么做?
相同的东西在控制台中可以很好地工作,每次都提供新的位置,但不在文件中。
答案 0 :(得分:0)
您应该调用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;
}
}