简体   繁体   中英

Write text to file System.IO.IOException

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.

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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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