簡體   English   中英

讀取和寫入同一流中的文件

[英]Read and write to a file in the same stream

我正在嘗試以相同的方式讀取和寫入同一文件,使得其他程序無法在兩者之間訪問該文件:

  FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);               
  StreamReader sr = new StreamReader(fs);
  StreamWriter sw = new StreamWriter(fs);
  newString = sr.ReadToEnd() + "somethingNew";
  sw.Write(newString);
  fs.Close();

該文件永遠不會被寫入。 如果我調試,則可以看到讀取器設法獲取文件的內容,但是寫入器似乎無法寫入該文件。 什么都沒發生。

我一直在看這個問題 ,似乎和我的一樣。 但是,我無法使其正常工作。

只需Flush對文件的更改,請具有sw.Flush(); 在關閉流之前。 喜歡:

string filePath = "test.txt";
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);
newString = sr.ReadToEnd() + "somethingNew";
sw.Write(newString);
sw.Flush(); //HERE
fs.Close();

您可能會看到本文同時在C#中讀寫文件 (打開多個流進行讀寫)

如上所述,只需添加Flush()即可強制將流中保存的數據寫入文件。 在評論中,您提到您以前使用了“使用”語句,但此操作無效。

簡單地說,原因如下:

  1. using語句會自動調用Flush(),因此您不必這樣做。

  2. 當您處置StreamReader(或StreamWriter)時(例如使用“ using”語句),內部流對象也會被處置,並且您將失去流的句柄。

@EJS一個簡單的靜態方法,如果不存在新文件,則可以使用它創建新文件;如果存在,則可以寫入同一文件

使用簡單

string path = @"C:\SomePath\Name.txt";

if (!System.IO.File.Exists(path))
{
    WriteAndOrAppendText(path, "File Created");
}
else if (System.IO.File.Exists(path))
{
    WriteAndOrAppendText(path, "New Boot.");             
}

private static void WriteAndOrAppendText(string path, string strText)
{
    if (!File.Exists(path))
    {
        using (StreamWriter fileStream = new StreamWriter(path, true))
        {
            fileStream.WriteLine(strText);
            fileStream.Flush();
            fileStream.Close();
        }
    }
    else
    {
        using (StreamWriter fileStream2 = new StreamWriter(path, true))
        {
            fileStream2.WriteLine(strText);
            fileStream2.Flush();
            fileStream2.Close();
        }
    }
}

為了能夠創建文件,追加文件並讀取其中的數據,同時仍允許應用程序對其進行寫入(我相信您正在嘗試這樣做),我創建了以下設置:

    string path = @"C:\SomePath\MyLogFile.txt";

    public static string Log(string Message)
    {
        try
        {
            if (File.Exists(path) == false)
                File.Create(path).Close();  // need this .Close()!!!

            logCounter++;
            string logString = logCounter + "   " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + Message + Environment.NewLine;

            using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(logString);
                }
            }

            return logString; // only necessary so we can return an error in the Exception block
        }
        catch (Exception ex)
        {
            return "Logger:  Cannot log data. " + ex.ToString();
        }
    }

它實際上需要使用FileAccess.Write如果你FileMode.Append -而不是能夠使用FileAccess.ReadWrite -但我發現並不重要,因為無論被寫會被關閉,刷新到該文件,我仍可以使用這些文件打開文件並讀取文件(不會被鎖定並留空)。 我有sw.Write()是因為我將Environment.NewLine添加到我的logString ,但我可以完成sw.WriteLine()並刪除它(如果我想這樣做的sw.WriteLine()

一個警告:如果路徑很長, File.Exists()出現問題-記不住限制了,但是只知道有一個限制,所以不要將要寫入的文件放在多個層次上。 越少越好。

暫無
暫無

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

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