如何在.Net 核中读写文件?

在.Net Core 中读/写文件有哪些选项?

我工作在我的第一个.Net 核心应用程序,并寻找 File.Read*/File.Write*函数(System.IO.Net)替代品。

140673 次浏览
FileStream fileStream = new FileStream("file.txt", FileMode.Open);
using (StreamReader reader = new StreamReader(fileStream))
{
string line = reader.ReadLine();
}

使用 System.IO.FileStreamSystem.IO.StreamReader。你也可以使用 System.IO.BinaryReaderSystem.IO.BinaryWriter

包裹: System.IO.FileSystem

System.IO.File.ReadAllText("MyTextFile.txt"); ?

用途:

File.ReadAllLines("My textfile.txt");

参考资料: https://msdn.microsoft.com/pt-br/library/s2tte0y1(v=vs.110).aspx

写作:

using (System.IO.StreamWriter file =
new System.IO.StreamWriter(System.IO.File.Create(filePath).Dispose()))
{
file.WriteLine("your text here");
}
    public static void Copy(String SourceFile, String TargetFile)
{


FileStream fis = null;
FileStream fos = null;


try
{
Console.Write("## Try No. " + a + " : (Write from " + SourceFile + " to " + TargetFile + ")\n");


fis = new FileStream(SourceFile, FileMode.Open, FileAccess.ReadWrite);
fos = new FileStream(TargetFile, FileMode.Create, FileAccess.ReadWrite);


int intbuffer = 5242880;
byte[] b = new byte[intbuffer];


int i;
while ((i = fis.Read(b, 0, intbuffer)) > 0)
{
fos.Write(b, 0, i);
}


Console.Write("Writing file : " + TargetFile + " is successful.\n");


break;
}
catch (Exception e)
{
Console.Write("Writing file : " + TargetFile + " is unsuccessful.\n");
Console.Write(e);
}
finally
{
if (fis != null)
{
fis.Close();
}
if (fos != null)
{
fos.Close();
}
}
}

上面的代码将读取一个大文件并写入一个新的大文件。“ intbuffer”值可以设置为1024的倍数。当源文件和目标文件都打开时,它按字节读取大文件并按字节写入新的目标文件。它不会消失在记忆中。

用于将任何文本写入文件。

public static void WriteToFile(string DirectoryPath,string FileName,string Text)
{
//Check Whether directory exist or not if not then create it
if(!Directory.Exists(DirectoryPath))
{
Directory.CreateDirectory(DirectoryPath);
}


string FilePath = DirectoryPath + "\\" + FileName;
//Check Whether file exist or not if not then create it new else append on same file
if (!File.Exists(FilePath))
{
File.WriteAllText(FilePath, Text);
}
else
{
Text = $"{Environment.NewLine}{Text}";
File.AppendAllText(FilePath, Text);
}
}

用于从文件读取文本

public static string ReadFromFile(string DirectoryPath,string FileName)
{
if (Directory.Exists(DirectoryPath))
{
string FilePath = DirectoryPath + "\\" + FileName;
if (File.Exists(FilePath))
{
return File.ReadAllText(FilePath);
}
}
return "";
}

这里的参考资料 这个是官方的微软文档链接。

在 Net Core 2.1中工作

    var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "email", "EmailRegister.htm");


string SendData = System.IO.File.ReadAllText(file);