在按钮单击并显示内容时读取多个文本文件
我最初有一个Fileupload工具来上传文本文件,操纵其内容并显示到列表框或文本框中。然而,限制是Fileupload仅支持单个上传,至少对于我正在使用的.Net Framework版本。在按钮单击并显示内容时读取多个文本文件
我打算做的只是使用按钮控件并删除Fileupload。点击按钮后,我需要读取指定文件夹路径内的文本文件,然后首先显示多行文本框内的内容。 (不仅仅是文件名)这是我的书面代码,它不起作用。
protected void btnGetFiles_Click(object sender, EventArgs e)
{
string content = string.Empty;
DirectoryInfo dinfo = new DirectoryInfo(@"C:\samplePath");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
//ListBox1.Items.Add(file.Name);
content += content;
}
txtContent.Text = content;
}
因为你的是基于web的应用程序,你不能访问像c:\\..
这样的物理路径,所以你应该使用Server.MapPath(根据注释,你不需要使用Server.MapPath获取文件)。然后为了获得内容,你可以尝试如下:
protected void btnGetFiles_Click(object sender, EventArgs e)
{
try
{
StringBuilder content = new StringBuilder();
if (Directory.Exists(@"C:\samplePath"))
{
// Execute this if the directory exists
foreach (string file in Directory.GetFiles(@"C:\samplePath","*.txt"))
{
// Iterates through the files of type txt in the directories
content.Append(File.ReadAllText(file)); // gives you the conent
}
txtContent.Text = content.ToString();
}
}
catch
{
txtContent.Text = "Something went wrong";
}
}
实际上先生,该应用程序现在用于本地使用,因此,如果我正在使用绝对路径。当前的代码实际上可以找到路径,唯一的问题是只有文件的内容没有被读取。只有文件名。当我尝试代码时,预计我有一个虚拟路径必须被编码的错误。 – rickyProgrammer
@rickyProgrammer:好的,然后继续用'C:\ samplePath''代替'Server.MapPath(“相对路径在这里)”并检查它是否工作;查看更新后的代码 –
感谢如果我喜欢它在gridview中显示? – rickyProgrammer
你写了content += content;
,就是这个问题。将其更改为content += file.Name;
,它将起作用。
仍然没有输出先生。 – rickyProgrammer
对不起,你是正确的在那里,但它显示的文件名,我如何显示每个文件的内容 – rickyProgrammer
有一个非常好的示例如何从https:// msdn中的.txt文件中读取文本.microsoft.com/en-us/library/db5x7c0d(v = vs.110).aspx –
只是一个FYI,.NET框架与多个文件上传无关。这是纯粹的客户端/ IIS工作。要看看如何允许多个文件上传,看看[这个SO问题](http://stackoverflow.com/questions/17441925/how-to-choose-multiple-files-using-file-upload-control) – Icemanind
因为我红色的某处Fileupload工具可以在最新版本中具有multipleUpload功能。感谢虽然修正 – rickyProgrammer