将文本写入文件System.IO.IOException [英] Write text to file System.IO.IOException

查看:81
本文介绍了将文本写入文件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);
    }
}

我遇到一个错误,告诉我该进程无法使用File at(path ..),因为该文件已在使用中.我尝试重新启动,然后删除File(它实际上工作了一次),但是似乎什么也没用.我可以写不同的方式使其正常工作,并且每次启动它都会创建一个新文件吗?

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.

推荐答案

您应该调用StreamWriter.Flush()或设置StreamWriter.AutoFlush = true

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

这篇关于将文本写入文件System.IO.IOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆