vc *_* 74 511
使用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);
Run Code Online (Sandbox Code Playgroud)
Bal*_*i C 155
此外File.ReadAllText
,File.ReadAllLines
和File.WriteAllText
(距离和类似佣工File
所示类),另一种答案,你可以使用StreamWriter
/ StreamReader
班.
编写文本文件:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
Run Code Online (Sandbox Code Playgroud)
阅读文本文件:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readMeText = readtext.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
笔记:
readtext.Close()
而不是using
,但在异常的情况下它不会关闭文件/读取器/写入器using
/ Close
是"为什么数据不写入文件"的常见原因.小智 18
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");
}
}
Run Code Online (Sandbox Code Playgroud)
Ank*_*ass 11
using (var file = File.Create("pricequote.txt"))
{
...........
}
using (var file = File.OpenRead("pricequote.txt"))
{
..........
}
Run Code Online (Sandbox Code Playgroud)
一旦完成,它就简单,容易并且还可以处理/清理对象.
小智 10
从文件读取并写入文件的最简单方法:
//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);
}
Run Code Online (Sandbox Code Playgroud)
@AlexeiLevenkov用另一种"最简单的方法"指出了扩展方法.它只需要一点点编码,然后提供绝对最简单的读/写方式,而且它可以根据您的个人需求灵活地创建变化.这是一个完整的例子:
这定义了string
类型的扩展方法.请注意,唯一真正重要的是带有extra关键字的函数参数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
Run Code Online (Sandbox Code Playgroud)
这是如何使用static
,注意它自动引用到string extension method
:
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
Run Code Online (Sandbox Code Playgroud)
我自己永远都找不到,但它很有效,所以我想分享一下.玩得开心!
读取时最好使用OpenFileDialog控件浏览到要读取的任何文件。查找下面的代码:
不要忘记添加以下using
语句来读取文件:using System.IO;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
Run Code Online (Sandbox Code Playgroud)
要写入文件,可以使用方法File.WriteAllText
。
或者,如果您确实是关于行的:
System.IO.File还包含一个静态方法WriteAllLines,因此您可以执行以下操作:
IList<string> myLines = new List<string>()
{
"line1",
"line2",
"line3",
};
File.WriteAllLines("./foo", myLines);
Run Code Online (Sandbox Code Playgroud)
这些是写入文件和从文件读取的最佳和最常用的方法:
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);
Run Code Online (Sandbox Code Playgroud)
我在大学里曾教过的一种旧方法是使用流读取器/流写入器,但是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
Run Code Online (Sandbox Code Playgroud)
通过文件资源管理器/打开文件对话框从用户获取文件名(您将需要使用它来选择现有文件)。
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
Run Code Online (Sandbox Code Playgroud)
从现有文件获取文本:
private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
string sFileNameAndPath = getFileNameFromUser();
txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}
Run Code Online (Sandbox Code Playgroud)