在c#中有很多不同的方法来读写文件(文本文件,而不是二进制文件)。
我只需要一些简单的东西,使用最少的代码,因为我将在我的项目中大量使用文件。我只需要一些字符串,因为我所需要的是读写字符串。
在c#中有很多不同的方法来读写文件(文本文件,而不是二进制文件)。
我只需要一些简单的东西,使用最少的代码,因为我将在我的项目中大量使用文件。我只需要一些字符串,因为我所需要的是读写字符串。
当前回答
以下是最好的和最常用的文件读写方法:
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. File.)。IO import语句),并查看所有可用的方法。下面是使用Windows窗体应用程序从文本文件(.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
}
其他回答
private void Form1_Load(object sender, EventArgs e)
{
//Write a file
string text = "The text inside the file.";
System.IO.File.WriteAllText("file_name.txt", text);
//Read a file
string read = System.IO.File.ReadAllText("file_name.txt");
MessageBox.Show(read); //Display text in the file
}
@AlexeiLevenkov指出了另一种“最简单的方法”,即扩展方法。它只需要一点点编码,然后提供绝对最简单的读/写方式,再加上它提供了根据个人需求创建变化的灵活性。下面是一个完整的例子:
这定义了字符串类型的扩展方法。注意,唯一真正重要的是带有额外关键字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
我自己永远不会发现这个,但它很棒,所以我想分享这个。玩得开心!
在读取时使用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方法。
以下是最好的和最常用的文件读写方法:
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. File.)。IO import语句),并查看所有可用的方法。下面是使用Windows窗体应用程序从文本文件(.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
}
从文件中读取并写入文件的最简单方法:
//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);
}