C# - 日志类IO异常

时间:2015-01-27 16:16:13

标签: c#

我的Faillog课程中出现“正在被另一个进程使用”的错误。它的代码如下。它发生在Log方法中的“using(StreamWriter sw = new StreamWriter(path + file,true))”行中。我不知道我做错了什么,因为似乎没有其他东西正在访问该文件。这似乎也是不可能的,因为在首次运行程序时会创建类的实例,然后在两秒钟后使用它时,它会以某种方式被另一个进程使用。我想找出导致这个错误的原因的一些帮助。

class Faillog
{
    #region Private Variables
    //The location of the Faillog file.
    private string path;

    //The name of the file used for marking failures.
    private string file;
    #endregion

    #region Constructor
    public Faillog(string p = @"C:\RH Faillog\", string f = "default")
    {
        path = p;
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        if (f == "default")
        {
            file = "Faillog_" + DateTime.Now.ToShortDateString().Replace("/", "-") + ".txt";
        }
        else
        {
            file = f;
        }

        if (!File.Exists(path + file))
        {
            File.Create(path + file);
        }
    }
    #endregion

    #region Getters
    public string GetPath()
    {
        return path;
    }

    public string GetFile()
    {
        return file;
    }
    #endregion

    #region Public Methods
    //Logs a fail record into the file.
    public void Log(string name)
    {
        using (StreamWriter sw = new StreamWriter(path + file, true))
        {
            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + ": " + name + " failed.");
        }
    }
    #endregion

2 个答案:

答案 0 :(得分:1)

您需要关闭该文件;

   file.Flush();
    file.Close();

答案 1 :(得分:0)

File.Create返回您忽略的FileStream,因此基础文件句柄不会及时释放(和关闭)。

您无论如何都不需要显式创建文件。如果文件不存在,StreamWriter应该为您创建文件。