C# 使用从 FileStream 创建的 StreamWriter 移动到文件末尾

C# move to end of file with StreamWriter created from FileStream

我需要从 FileStream 对象创建一个 StreamWriter 并将一些文本附加到 文件。假定正在使用的 FileStream 对象是使用 FileMode.OpenOrCreate 和 FileAccess.ReadWrite 创建的。我有:

using (FileStream fs = GetCurrentFileStream())
{
    StreamWriter sw = new StreamWriter(fs);
    sw.WriteLine("StringToAppend");
    sw.Flush();
}

然而,这只是从头开始覆盖文件。如何移动到文件末尾?在创建 FileStream 后,是否可以将 FileMode 更改为 Append 并将 FileAccess 更改为 Write?

编辑:如上所述,我需要使用 FileStream 对象执行此操作。 Open existing file, append a single line 的答案假设我可以从我没有的文件路径创建一个新的 StreamWriter。

编辑 2:添加了 GetCurrentFileStream() 的截断版本。

    public static FileStream GetCurrentFileStream()
    {
        String fileName = getFileName();
        FileStream fs = OpenFileWhenAvailable(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
    }

    public static FileStream OpenFileWhenAvailable(String fileName, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
    {
        int tries = 0;
        int timeout = 10 * 1000;
        while (true)
        {
            tries++;
            try
            {
                return new FileStream(fileName, fileMode, fileAccess, fileShare);
            }
            catch (IOException ex)
            {
                if (tries * 100 > timeout)
                {
                    return null;
                }
                else
                {
                    System.Threading.Thread.Sleep(100);
                }
            }
        }
    }

GetCurrentFileStream 在几个不同的上下文中使用,因此不能直接更改 FileMode 和 FileAccess。我不希望只为这种情况制作一个单独的 GetCurrentFileStream 版本,这就是为什么我要问是否有一种方法可以跳转到流的末尾并在已创建 FileStream 对象时附加一个字符串。

如果我没理解错的话,您想将您的行附加到创建的文件中:

using (FileStream fs = GetCurrentFileStream())
{
    StreamWriter sw = new StreamWriter(fs, true);
    sw.WriteLine("StringToAppend");
    sw.Flush();
}

通过重载 StreamWriter 构造函数,您可以选择是追加文件还是覆盖文件。

如果你展示你的方法实现,那将是非常酷的 GetCurrentStream():

using (FileStream fileStream = new FileStream(fileName,FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
   sw.WriteLine(something);
}

更新:

using (FileStream fs = GetCurrentFileStream())
{
   StreamWriter sw = new StreamWriter(fs);
   long endPoint=fs.Length;
   // Set the stream position to the end of the file.        
   fs.Seek(endPoint, SeekOrigin.Begin);
   sw.WriteLine("StringToAppend");
   sw.Flush();
 }

如果你真的真的想要,你可以把它美化....

    static int iMaxLogLength = 15000;
    static int iTrimmedLogLength = -2000;

    static public void writeToFile2(string strMessage, string strLogFileDirectory, int iLogLevel)
    {
        string strFile = strLogFileDirectory + "log.log";

        try
        {
            FileInfo fi = new FileInfo(strFile);

            Byte[] bytesRead = null;

            if (fi.Length > iMaxLogLength)
            {
                using (BinaryReader br = new BinaryReader(File.Open(strFile, FileMode.Open)))
                {
                    // Go to the end of the file and backup some
                    br.BaseStream.Seek(iTrimmedLogLength, SeekOrigin.End);

                    // Read that.
                    bytesRead = br.ReadBytes((-1 * iTrimmedLogLength));
                }
            }

            byte[] newLine = System.Text.ASCIIEncoding.ASCII.GetBytes(Environment.NewLine);

            FileStream fs = null;
            if (fi.Length < iMaxLogLength)
                fs = new FileStream(strFile, FileMode.Append, FileAccess.Write, FileShare.Read);
            else
                fs = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.Read);

            using (fs)
            {
                if (bytesRead != null)
                {
                    fs.Write(bytesRead, 0, bytesRead.Length);
                    fs.Write(newLine, 0, newLine.Length);
                    Byte[] lineBreak = Encoding.ASCII.GetBytes("### " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " *** *** *** New Log Start Position *** *** *** *** ###");
                    fs.Write(lineBreak, 0, lineBreak.Length);
                    fs.Write(newLine, 0, newLine.Length);
                }
                Byte[] sendBytes = Encoding.ASCII.GetBytes(strMessage);
                fs.Write(sendBytes, 0, sendBytes.Length);
                fs.Write(newLine, 0, newLine.Length);
            }
        }
        catch (Exception ex)
        {
            ; // Write to event or something
        }
    }