在C#中,有很多不同的方法可以读写文件(文本文件,而非二进制文件)。
我只需要一种简单且使用最少量代码的方法,因为在我的项目中我将经常处理文件。我只需要处理 string
类型,因为我只需要读写 string
。
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
...
// Open the file to read from.
string readText = File.ReadAllText(path);
这个页面列出了常见I/O任务的各种辅助方法。
File.ReadAllText
、File.ReadAllLines
和File.WriteAllText
(以及File
类的类似帮助程序),您还可以使用StreamWriter
/StreamReader
类。
编写文本文件:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
读取文本文件:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readText = readtext.ReadLine();
}
注意:
readtext.Dispose()
代替using
,但在出现异常时它不会关闭文件/读取器/写入器。using
/Close
是“为什么数据没有写入文件”的非常普遍的原因。using System.IO;
才能使用StreamWriter和StreamReader。 - fatnew StreamWriter("write.txt", true)
。如果文件不存在,它将创建一个新文件,否则它会追加到现有文件中。 - ArieKanarieFileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
using(StreamReader sr = new StreamReader(fs))
{
using (StreamWriter sw = new StreamWriter(Destination))
{
sw.Writeline("Your text");
}
}
fs
? - LuckyLikeyStreamReader(Stream)
构造函数时,StreamReader对象在调用StreamReader.Dispose时会对提供的Stream对象调用Dispose()
。还有另一个构造函数,它接受一个leaveOpen
参数,如果您不想让Dispose
也处理流,则可以使用该参数。 - user276648从文件读取和写入文件的最简单方式:
//Read from a file
string something = File.ReadAllText("C:\\Rfile.txt");
//Write to a file
using (StreamWriter writer = new StreamWriter("Wfile.txt"))
{
writer.WriteLine(something);
}
File.WriteAllText
来进行写入操作? - Peter Mortensenusing (var file = File.Create("pricequote.txt"))
{
...........
}
using (var file = File.OpenRead("pricequote.txt"))
{
..........
}
简单易用,同时在完成后自动清理/释放对象。
@AlexeiLevenkov指出了另一种"最简单的方法",即使用扩展方法。只需编写一点代码,便可提供绝对最容易的读取/写入方式,并且它还提供了根据您个人需求创建变化的灵活性。以下是完整的示例:
这定义了在string
类型上的扩展方法。请注意,唯一真正重要的是带有额外关键字this
的函数参数,这使它引用附加到方法的对象。类名不重要; 必须声明类和方法为静态。
using System.IO;//File, Directory, Path
namespace Lib
{
/// <summary>
/// Handy string methods
/// </summary>
public static class Strings
{
/// <summary>
/// Extension method to write the string Str to a file
/// </summary>
/// <param name="Str"></param>
/// <param name="Filename"></param>
public static void WriteToFile(this string Str, string Filename)
{
File.WriteAllText(Filename, Str);
return;
}
// of course you could add other useful string methods...
}//end class
}//end ns
这是如何使用字符串扩展方法
,请注意它自动引用Strings类
:
using Lib;//(extension) method(s) for string
namespace ConsoleApp_Sandbox
{
class Program
{
static void Main(string[] args)
{
"Hello World!".WriteToFile(@"c:\temp\helloworld.txt");
return;
}
}//end class
}//end ns
我自己永远找不到这个,但它很有效,所以我想分享一下。祝你们玩得开心!
using System.IO;
File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it.
File.ReadAllText(sFilePathAndName);
在大学里我学习的旧方法是使用流读取器/流写入器,但文件I/O方法更为简洁,需要的代码行数更少。您可以在IDE中键入“File.”(确保包括System.IO导入语句)并查看所有可用的方法。以下是使用Windows Forms应用程序从文本文件(.txt)读取/写入字符串的示例方法。
将文本追加到现有文件:
private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
string sTextToAppend = txtMainUserInput.Text;
//first, check to make sure that the user entered something in the text box.
if (sTextToAppend == "" || sTextToAppend == null)
{MessageBox.Show("You did not enter any text. Please try again");}
else
{
string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
if (sFilePathAndName == "" || sFilePathAndName == null)
{
//MessageBox.Show("You cancalled"); //DO NOTHING
}
else
{
sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
File.AppendAllText(sFilePathAndName, sTextToAppend);
string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
}//end nested if/else
}//end if/else
}//end method AppendTextToExistingFile_Click
private string getFileNameFromUser()//returns file path\name
{
string sFileNameAndPath = "";
OpenFileDialog fd = new OpenFileDialog();
fd.Title = "Select file";
fd.Filter = "TXT files|*.txt";
fd.InitialDirectory = Environment.CurrentDirectory;
if (fd.ShowDialog() == DialogResult.OK)
{
sFileNameAndPath = (fd.FileName.ToString());
}
return sFileNameAndPath;
}//end method getFileNameFromUser
private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
string sFileNameAndPath = getFileNameFromUser();
txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}
如果你真的关注代码行数:
System.IO.File还包含一个静态方法WriteAllLines,所以你可以这样做:
IList<string> myLines = new List<string>()
{
"line1",
"line2",
"line3",
};
File.WriteAllLines("./foo", myLines);
当阅读时,使用OpenFileDialog控件浏览您想要阅读的任何文件是很好的。以下是代码:
不要忘记添加以下using
语句以读取文件:using System.IO;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
要写文件,您可以使用方法File.WriteAllText
。
class Program
{
public static void Main()
{
//To write in a txt file
File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");
//To Read from a txt file & print on console
string copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
Console.Out.WriteLine("{0}",copyTxt);
}
}
string.Write(filename)
的方向寻找答案。为什么微软的解决方案比我的更简单/更好呢? - Roland"foo".Write(fileName)
,你可以很容易地创建一个扩展来实现,例如public static Write(this string value, string fileName) { File.WriteAllText(fileName, value);}
,并在你的项目中使用它。 - Alexei Levenkov