簡體   English   中英

.net核心中StreamReader的更短解決方案

[英]A shorter solution to StreamReader in .net core

我有這個基本代碼,用於在VS Code中使用帶有Dotnet Core的StreamReader讀取文件。 我可以在Visual Studio中使用.net new StreamReader("file.json")進行類似的操作,它看起來小巧緊湊。

我正在尋找dotnet核心中的另一個類,它可以用更少的代碼實現類似的結果

 using System;
 using System.IO;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            StreamReader myReader = new StreamReader(new FileStream("project.json", FileMode.Open, FileAccess.Read)); 
            string line = " "; 

            while(line != null)
            {
                line = myReader.ReadLine(); 
                if(line != null)
                {
                    Console.WriteLine(line); 
                }
            }

            myReader.Dispose();
        }
    }
}

在完整的框架中,close方法對Dispose來說是多余的。 關閉流的推薦方法是通過using語句調用Dispose,以確保即使發生錯誤也會關閉流。

您可以使用System.IO.File.OpenText()直接創建StreamReader。

在這里,您只需打開和關閉StreamReader即可:

using (var myReader = File.OpenText("project.json"))
{
    // do some stuff
}

File類位於System.IO.FileSystem nuget包中

代碼較少的類似結果? 刪除你不必要的代碼......這不會工作???

try {
  using (StreamReader myReader = File.OpenText("project.json")) {
    string line = "";
    while ((line = myReader.ReadLine()) != null) {
      Console.WriteLine(line);
    }
  }
}
catch (Exception e) {
  MessageBox.Show("FileRead Error: " + e.Message);
}

暫無
暫無

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

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