c# - .net core 中 StreamReader 的更短解决方案

标签 c# .net-core .net-core-rc2

我有这个基本代码,可以在 VS Code 中使用带有 Dotnet Core 的 StreamReader 读取文件。我可以在 Visual Studios 中使用 .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
}

文件类在 System.IO.FileSystem 中nuget包

关于c# - .net core 中 StreamReader 的更短解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057784/

相关文章:

c# - 组合 C# 和 C++ 项目适用于 x86 和 x64,但不适用于 ARM

c# - 为什么我不应该使用反射实现 Equals 和 GetHashCode?

c# - 如何检查表达式树中参数的类型(类似于 'is' 关键字)

c# - 如何在 .NET Standard 2.0/Core 2.1 中使用 PrivateKey 创建 X509Certificate2?

c# - 合并两个 Observable 时保留排序

c# - 编码 va_list

c# - 在 asp.net 核心项目中获取 Azure Active Directory 组

c# 如何连接一个 var 与另一个 var 以指向应用程序 SettingsName?

c# - ASP.NET Core HTTPRequestMessage 返回奇怪的 JSON 消息

c# - 无法解决 .NET Framework 的包错误,版本 = v4.5.1