如何在 .NET Core 中写入文件?

62
我想在.NET Core中使用蓝牙低功耗功能(特别是BluetoothLEAdvertisementWatcher)编写一个扫描器,将信息记录到文件中。这应该作为桌面应用程序运行,并最好作为命令行应用程序。
类似于System.IO.StreamWriter(string)的构造函数显然是不可用的。我怎样才能创建文件并写入其中?
我同样希望能够使用System.Console.WriteLine(string),但在.NET Core中似乎也无法使用。
更新:为了澄清,如果我可以有一个像这样运行而没有错误的程序,我就可以开始了。
using System;
using Windows.Devices.Bluetooth.Advertisement;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher();
            Console.WriteLine("Hello, world!");
        }
    }
}

更新2:这是project.json文件:

{
  "dependencies": {
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
  },
  "frameworks": {
    "uap10.0": {}
  },
  "runtimes": {
    "win10-arm": {},
    "win10-arm-aot": {},
    "win10-x86": {},
    "win10-x86-aot": {},
    "win10-x64": {},
    "win10-x64-aot": {}
  }
}

运行命令dotnet -v run的输出包含此错误消息:

W:\src\dotnet_helloworld>dotnet -v run
...
W:\src\dotnet_helloworld\Program.cs(2,15): error CS0234: The type or namespace name 'Devices' does not exist in the namespace 'Windows' (are you missing an assembly reference?)
...

你需要在WinRT中做同样的事情吗?http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html - Matthew Watson
你能分享一下 project.json 文件吗?你可能缺少了一些包的引用。 - Victor Hurdugaci
@VictorHurdugaci 我已经编辑了问题,包括我尝试过的一个project.json文件以及产生的错误消息。毫无疑问,引用是错误的,我有点盲目。这个特定的project.json是从Visual Studio 2015项目模板中获取的,用于.NET Core项目。 - gauss256
7个回答

104

这段代码就是我提出问题时所寻找的框架,它只使用.NET Core中可用的工具。

var watcher = new BluetoothLEAdvertisementWatcher();

var logPath = System.IO.Path.GetTempFileName();
var logFile = System.IO.File.Create(logPath);
var logWriter = new System.IO.StreamWriter(logFile);
logWriter.WriteLine("Log message");
logWriter.Dispose();

4
做得很好。我猜大约六个月后,它会有几百个赞。 - GDB

34

这是我正在使用的解决方案。它使用更少的代码行并且完美地完成了工作。它也非常兼容 .NET core 2.0。

using (StreamWriter writer = System.IO.File.AppendText("logfile.txt"))
{
    writer.WriteLine("log message");
}

4
如果你想替换文本,使用System.IO.File.CreateText代替System.IO.File.AppendText - Harsha Siriwardana

25

更好的是:

using System.IO;

var logPath = Path.GetTempFileName();
using (var writer = File.CreateText(logPath)) // or File.AppendText
{
    writer.WriteLine("log message"); //or .Write(), if you wish
}

如果你喜欢写更少的代码,上述内容可以这样重写:

using (var writer = System.IO.File.CreateText(System.IO.Path.GetTempFileName()))
{
    writer.WriteLine("log message"); //or .Write(), if you wish
}

10

截至今天,使用RTM似乎也有这种更简短的方式:

var watcher = new BluetoothLEAdvertisementWatcher();

var logPath = System.IO.Path.GetTempFileName();
var logWriter = System.IO.File.CreateText(logPath);
logWriter.WriteLine("Log message");
logWriter.Dispose();

3

要在.NET Core中写入文件,您可以使用两种方法:

  1. AppendText()
  2. CreateText()

这两种方法是位于System.IO命名空间中File类的静态成员。它们之间的区别在于一个追加到现有文件,而另一个覆盖文件。

使用示例:

AppendText

using (StreamWriter writer = System.IO.File.AppendText("file.txt"))
{
    writer.WriteLine("message");
}

CreateText

using (StreamWriter writer = System.IO.File.CreateText("file.txt"))
{
    writer.WriteLine("message");
}

1
你可以通过使用 corefx git 仓库来获取 System.IO 引用。这将使你正在寻找的 StreamWrite(string) 构造函数可用。
此仓库还将为你提供正在寻找的 Console.WriteLine(string) 函数。

听起来不错,但我还是卡住了。我已经安装并构建了CoreFX。现在该怎么办?我要在Visual Studio项目中添加它作为引用吗?我要使用dotnet命令准备和运行我的程序吗?我已经在原始问题中添加了一个代码片段,以澄清我想要实现的第一步。 - gauss256
一旦构建完成,您需要将其添加为引用,然后您就可以通过在文件顶部加入 using System.IO; 来包含 System.IO 库。 - FanManPro
可能有一种方法可以做到这一点,但是我尝试将CoreFX的引用包含在.NET Core中时,遇到了冲突。 - gauss256

1
这是一个异步的FileWriter类。

using System.IO;
public static class AsyncFileWriter
{
    public static async Task WriteToFile(string content)
    {
        var logPath = @"SOME_PATH\log.txt";
        using (var writer = File.CreateText(logPath))
        {
            await writer.WriteLineAsync(content); 
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接