如何使用C#将文本文件中的文本添加到字符串 [英] How to add text in a textfile to a string using C#
问题描述
我使用打开文件对话框选择了一个文件。
然后我需要将文件中的所有文本内容添加到字符串变量中。
怎么做。
I have selected a file using open file dialog.
Then I need to add all the text contents in the file to a string variable.
How to do so.
推荐答案
你可以这样做:
You could just do this:
string s = "my original content";
s += File.ReadAllText(path);
但效率非常低:
But that is pretty inefficient:
string s = "my original content";
string fileData = File.ReadAllText(path);
StringBuilder sb = new StringBuilder(s.Length + fileData.Length);
sb.Append(s);
sb.Append(fileData);
s = sb.ToString();
可能会更好,特别是如果你这么做,可以重复使用StringBuilder
我正在使用打开文件对话框在运行时选择5个文件。
如何创建五个字符串运行时将所有文本文件存储在适当的字符串中
试试这个:
Might be better, particularly if you are doing this a lot and can re-use the StringBuilder
"I am using open file dialog to select 5 files at runtime.
How to create five strings at runtime to store all text files in appropriate strings"
Try this:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
List<string> data = new List<string>();
foreach (string file in ofd.FileNames)
{
data.Add(File.ReadAllText(file));
}
}
或者如果您更喜欢Linq:
Or this if you prefer Linq:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
string[] data = ofd.FileNames.Select(f => File.ReadAllText(f)).ToArray();
}
您可以从文本文件中读取内容如下:
You can read the content from a text file as the follows:
String yourFileFromDialog = "file location and file name";
String textFromFile = string.Empty;
try
{
using (StreamReader sr = new StreamReader(yourFileFromDialog))
{
textFromFile = sr.ReadToEnd();
}
}
catch (Exception e)
{
//exception handling
}
这里 [ ^ ]你可以阅读更多。
如果您的文件名有字符串数组,请执行以下操作:
Here[^] you can read more.
If you have a string array for your file names, do the follow:
string[] fileNames = //fill up from your dialog
String yourFileFromDialog = string.Empty,
textFromFile = string.Empty;
try
{
for(int i = 0; i < fileNames.length; i++)
{
yourFileFromDialog = fileNames[i];
using (StreamReader sr = new StreamReader(yourFileFromDialog))
{
textFromFile += sr.ReadToEnd();
}
}
}
catch (Exception e)
{
//exception handling
}
对于以后使用文件中的文本,您可以为您的类创建一个私有属性,并将其替换为textFromFile变量:
For the later usage of the text from the files you can make a private property to your class and append this instead of textFromFile variable:
private string textFromFiles = string.Empty;
Chk此代码:
Chk this code :
System.IO.StreamReader file = new System.IO.StreamReader(@"D:\test.txt");
String Line="";
String txtLine = "";
while ((Line = file.ReadLine()) != null)
{
txtLine = txtLine + Line;
}
file.Close();
textBox4.Text=txtLine;
这篇关于如何使用C#将文本文件中的文本添加到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!