Answers:
使用File.ReadAllText和File.WriteAllText。
这再简单不过了...
MSDN示例:
// 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);
"foo".Write(fileName)
,可以轻松创建扩展名,并public static Write(this string value, string fileName) { File.WriteAllText(fileName, value);}
在项目中使用它。
此外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
您的流如图对方的回答- stackoverflow.com/a/7571213/477420
using System.IO;
使用StreamWriter和StreamReader。
new StreamWriter("write.txt", true)
会产生重载:如果不存在不存在的文件,则会创建一个文件,否则会追加到现有文件。
FileStream 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
?
using (var file = File.Create("pricequote.txt"))
{
...........
}
using (var file = File.OpenRead("pricequote.txt"))
{
..........
}
操作简单,简单,并且在完成处理后还可以处置/清理对象。
@AlexeiLevenkov向我指出了另一种“最简单的方法”,即扩展方法。它只需要一点编码,然后提供绝对最简单的读/写方式,此外,它还提供了根据您的个人需求创建变体的灵活性。这是一个完整的示例:
这定义了string
类型的扩展方法。请注意,唯一真正重要的是带有extra关键字的function参数,该参数this
使它引用该方法所附加的对象。类名无关紧要;必须声明类和方法static
。
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
这是使用方法string extension method
,请注意,它会自动引用class 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);
我上大学时曾教过的旧方法是使用流读取器/流写入器,但是File I / O方法比较笨拙,并且需要更少的代码行。您可以输入“文件”。在您的IDE中(确保您包括System.IO import语句)并查看所有可用方法。下面是使用Windows Forms App从文本文件(.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
}
读取时最好使用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);
}
}
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
}
string.Write(filename)
。为什么Microsoft的解决方案比我的解决方案更简单/更好?