按钮单击并显示内容时读取多个文本文件

时间:2017-02-13 02:52:55

标签: c# asp.net vb.net

我最初有一个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;


        }

2 个答案:

答案 0 :(得分:1)

由于您的基于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";
      }

  }

答案 1 :(得分:0)

你写了content += content;,这就是问题所在。将其更改为content += file.Name;,它会有效。

相关问题