簡體   English   中英

如何使用C#4.0從Windows應用程序的客戶端中讀取服務器中的文本文件

[英]how to read text file in server from client in windows application using C# 4.0

如何使用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();

要訪問服務器上的文件,您需要做兩件事

  • 確保您使用的是有權訪問該文件的用戶

  • 將服務器地址路徑設置為\\ 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.您需要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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM