Write text to file System.IO.IOException

谁说胖子不能爱 提交于 2021-02-11 14:31:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!