簡體   English   中英

使用從FileStream創建的StreamWriter,C#移動到文件末尾

[英]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的答案,附加一行假設我可以從我沒有的文件路徑創建一個新的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
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM