簡體   English   中英

在StreamWriter中使用file.Close()

[英]Using file.Close() with StreamWriter

我在嘗試使用該文件時遇到問題。在此方法中使用StreamWriter關閉,它似乎不喜歡它。 有人可以演示如何做到這一點。 (之所以這樣,是因為另一個方法訪問了一個正在使用的文件,因此無法訪問,因為該文件仍在被另一個方法使用。)

到目前為止的代碼:

private static void TrimColon()
{
    using (StreamWriter sw = File.AppendText(@"process_trimmed.lst"))
    {
        StreamReader sr = new StreamReader(@"process_trim.lst");
        string myString = "";
        while (!sr.EndOfStream)
        {

            myString = sr.ReadLine();
            int index = myString.LastIndexOf(":");
            if (index > 0)
                myString = myString.Substring(0, index);

            sw.WriteLine(myString);
        }
    }
}

由於“使用”語句,StreamWriter也會關閉以及刷新。 因此,無需調用close。

private static void TrimColon(String inputFilePath, String outputFilePath)
{
    //Error checking file paths
    if (String.IsNullOrWhiteSpace(inputFilePath))
        throw new ArgumentException("inputFilePath");
    if (String.IsNullOrWhiteSpace(outputFilePath))
        throw new ArgumentException("outputFilePath");

    //Check to see if files exist? - Up to you, I would.

    using (var streamReader = File.OpenText(inputFilePath))
    using (var streamWriter = File.AppendText(outputFilePath))
    {
        var text = String.Empty;

        while (!streamReader.EndOfStream)
        {
            text = streamReader.ReadLine();

            var index = text.LastIndexOf(":");
            if (index > 0)
                text = text.Substring(0, index);

            streamWriter.WriteLine(text);
        }
    }
}

暫無
暫無

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

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