[英]How to read/write files in .Net Core?
在 .Net Core 中讀/寫文件有哪些選項?
我正在開發我的第一個 .Net Core 應用程序並尋找File.Read*
/ File.Write*
函數(來自.Net
System.IO
)替代方案。
System.IO.File.ReadAllText("MyTextFile.txt"); ?
FileStream fileStream = new FileStream("file.txt", FileMode.Open);
using (StreamReader reader = new StreamReader(fileStream))
{
string line = reader.ReadLine();
}
使用System.IO.FileStream和System.IO.StreamReader 。 您也可以使用System.IO.BinaryReader或System.IO.BinaryWriter 。
來寫:
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(System.IO.File.Create(filePath).Dispose()))
{
file.WriteLine("your text here");
}
適用於 Net Core 2.1
var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "email", "EmailRegister.htm");
string SendData = System.IO.File.ReadAllText(file);
使用:
File.ReadAllLines("My textfile.txt");
參考: https : //msdn.microsoft.com/pt-br/library/s2tte0y1(v = vs.110).aspx
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 "";
}
對於參考, 這是官方的Microsoft文檔鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.