首页 > 解决方案 > 将文本写入文件 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);
    }
}

我有一个错误告诉我该进程无法使用位于(路径..)的文件,因为它已在使用中。我尝试重新启动并删除文件(它实际上工作了一次)但似乎没有任何工作。我可以用不同的方式编写它以使其正常工作,并且每次启动它都会创建一个新文件吗?

另一个问题是,如果有人知道为什么它只保存一个位置......该位置每隔几毫秒更新一次,我想要该文件中的每个位置,而不仅仅是一个......我应该怎么做?

同样的事情在控制台中完美运行,每次也给出新位置,但不在文件中。

标签: c#fileexception

解决方案


您应该调用 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;
        }
    }

推荐阅读