问题
I have the following code to write some current positions down to a file :
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);
}
}
I have an error telling me that the process could not use the File at( path..) because its already in use. I tried restarting, and deleting the File( it actually worked one time) but nothing seems to work. Can I write it different so it works, and everytime I start it it makes a new file?
And another question is if somebody knows why it only saves one position...the position is renewed every few milliseconds and I want every position in that file, not only one..how am I supposed to do it?
Same thing works perfectly in the console, also giving the new positions every time, but not in the file.
回答1:
You should either call StreamWriter.Flush() or set StreamWriter.AutoFlush = true
Additionally before or after writing, I usually check whether the file is locked by another process:
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;
}
}
来源:https://stackoverflow.com/questions/53611950/write-text-to-file-system-io-ioexception