如何保存和打开自己的文件 C#

how to save and open your own file C#

当我在我的程序中按下保存按钮时,我想用我自己的扩展名保存一个文件。 (示例 .xyz

那我想通过这个程序打开它,读取里面的数据

我怎样才能做到这一点?

When I press the save button in my program, I want to save a file with my own extension. (Example .xyz). Do the following:

const string directory = @"D:\Temp"; // this can be any location you want

if (!Directory.Exists(directory))
    Directory.CreateDirectory(directory);

string path = Path.Combine(directory, "Test.custom");
if (!File.Exists(path))
{
    File.Create(path);

    // other logic
}

Then I want to open it and read the data inside it through this program.

string textFile = @"D:\Torrent\Test.custom";

using StreamReader sr = new StreamReader(textFile);
var line = sr.ReadToEnd();
Console.WriteLine(line);

如果您稍后想在文件中保存一些内容,最简单的方法是:

const string textFile = @"D:\Torrent\Test.custom";
string createText = $"Some text {Environment.NewLine}";
File.WriteAllText(textFile, createText);