如何使用C#4.0从Windows应用程序中的客户端读取服务器中的文本文件

时间:2014-02-21 09:27:14

标签: c# .net c#-4.0 client-server

如何使用C#4.0从Windows应用程序中的客户端读取服务器中的文本文件

并在客户端应用程序的文本框中显示相同内容

能够在本地阅读文本并在文本框中打印

但是从服务器怎么办?

下面是我为本地文件尝试的代码

string line;
StringBuilder sb = new StringBuilder();
int counter = 0;

using (StreamReader file = new StreamReader(path))
{
  while ((line = file.ReadLine()) != null)
      {
         if (line.Contains(searchstring))
          {
               if (line.Contains(searchfromdate)) //|| line.Contains(searchtodate)) 
                  {
                        sb.AppendLine(line.ToString());
                        counter++;
                  }
          }
      }
}

ResultTextBox.Text = sb.ToString();
CountLabel.Text = counter.ToString();

2 个答案:

答案 0 :(得分:2)

要访问服务器上的文件,您需要做两件事

  • 确保您使用的是有权访问该文件的用户

  • 将服务器地址路径设置为\ servername1 \ Folder \ file.txt

所以使用你的代码就必须有类似

的东西
string line;
string path = @"\\server1\TextFolder\Text.txt";
StringBuilder sb = new StringBuilder();
int counter = 0;

using (StreamReader file = new StreamReader(path))
{
  while ((line = file.ReadLine()) != null)
      {
         if (line.Contains(searchstring))
          {
               if (line.Contains(searchfromdate)) //|| line.Contains(searchtodate)) 
                  {
                        sb.AppendLine(line.ToString());
                        counter++;
                  }
          }
      }
}

ResultTextBox.Text = sb.ToString();
CountLabel.Text = counter.ToString();

答案 1 :(得分:1)

1。您需要Share服务器计算机中的文件夹,并向想要远程访问它的用户提供Read权限。

2。获取服务器计算机的IPAddressHostname,以便您可以访问共享文件夹。

3。现在准备文件路径如下:

示例:如果ServerName为MyServer123且FolderName为MyFolder,则FileName为myFile.txt

您的路径应为"\\MyServer123\MyFolder\MyFile.txt"

完整代码:

StringBuilder sb = new StringBuilder();
int counter = 0;
String path=@"\\MyServer123\MyFolder\MyFile.txt";
foreach(var line in File.ReadLines(path))
{
  if (line.Contains(searchstring) && (line.Contains(searchfromdate)))
  {
    sb.AppendLine(line);
    counter++;
  }
}
ResultTextBox.Text = sb.ToString();
CountLabel.Text = counter.ToString();