0

我创建了一个小类来创建日志。此类使用流写入器函数来执行此操作。

我写了一个日志,关闭日志后,我想重新打开,以附加一些数据。

我尝试了几个技巧,并且......我总是有一个例外告诉我“该文件被另一个进程使用”。

不过,我使用 close(),但是,我总是有这个异常。

这是我的课:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TEST
{
public class CLog
{
    private StreamWriter myWriter;

    public string Name
    {
        set { Name = value; }
        get
        {
            FileInfo myFile = new FileInfo(CompleteFileName);
            return myFile.Name;
        }

    }
    public string Directory
    {
        set { Directory = value; }
        get
        {
            FileInfo myFile = new FileInfo(CompleteFileName);
            return myFile.Directory.ToString();
        }
    }
    public string CompleteFileName { set; get; }

    public CLog(string _CompleteFileName)
    {
        CompleteFileName = _CompleteFileName;
    }

    public bool CreateLog()
    {
        try
        {
            myWriter = new StreamWriter(CompleteFileName);
            return true;            
        }
        catch (Exception ex  )
        {
            return false;
        }
    }

    public bool AppendTextToFile(string strText)
    {
        try
        {
            using (System.IO.StreamWriter sw = System.IO.File.AppendText(CompleteFileName))
            {
                sw.WriteLine(strText);
            }
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    public bool WriteLine(string strLine)
    {
        try
        {
            myWriter.WriteLine(strLine);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    public bool SaveFile()
    {
        try
        {
            myWriter.Close();
            myWriter.Dispose();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

}

请查看 AppendTextToFile。

这是用途:

monLog = new CLog("C:\\TEST.TXT"); 
if (monLog.CreateLog())
{
   monLog.WriteLine("");
   monLog.WriteLine("******");
   monLog.WriteLine("Some data");
   monLog.WriteLine("******");
   monLog.SaveFile();
   ...
   ....
   monLog.AppendTextToFile("** my AppendedData***);
   monLog.SaveFile();
}

任何人都知道为什么我有这个异常以及如何解决它?

非常感谢 :)

4

0 回答 0