2012-01-27 55 views
2

我想要做的是連接到遠程服務器並讀取文本文件,然後將其顯示在控制檯中。遠程服務器需要用戶名和密碼才能訪問。我想問問你們,做這件事的最好方法是什麼。嘗試使用C#Forms連接遠程服務器應用程序

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Runtime.InteropServices; 
using System.IO; 
using Microsoft.Win32.SafeHandles; 

namespace WebclientTest 
{ 


class Server 
{ 
    [DllImport("kernel32")] 
    static extern bool AllocConsole(); 

    WebClient client = new WebClient(); 

    private string hostName; 
    private string userName; 
    private string password; 

    //Constructor gets host username and password 
    public Server(string _hostName, string _userName, string _password) 
    { 
     hostName = _hostName; 
     userName = _userName; 
     password = _password; 
    } 

    public void Connect() 
    { 
     AllocConsole(); 
     //Console.WriteLine("HelloWorld"); 
     //Console.ReadLine(); 
     Uri uri = new Uri(hostName); 
     Console.WriteLine(uri.Host.ToString()); 
     string fileLocation = uri.Host+"\someDirectory.textfile.txt"; 
     StreamReader strRead = new StreamReader(fileLocation); 
     Console.Write(strRead.ReadLine()); 
    } 
} 

}

+0

什麼驗證類型?基本認證?形式? – 2012-01-27 03:44:35

回答

0

不知道這是最好的方式,但我已經通過映射一個驅動器,然後使用映射驅動器號訪問該文件做了類似的事情:

private void mapDrive(String strDrive, String strLocation, string strUser, string strPassword) 
    { 
     System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
     proc.EnableRaisingEvents = false; 
     proc.StartInfo.FileName = "net"; 
     proc.StartInfo.Arguments = "use " + @strDrive + " " + @strLocation + " " + @" /USER:" + @strUser + " " + @strPassword; 
     proc.Start(); 
     proc.WaitForExit(); 
    } 

完成後,請務必刪除映射:

private void unmapDrive(String strDrive) 
    { 
     System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
     proc.EnableRaisingEvents = false; 
     proc.StartInfo.FileName = "net"; 
     proc.StartInfo.Arguments = "use " + @strDrive + @" /delete /yes"; 
     proc.Start(); 
     proc.WaitForExit(); 
    } 
相關問題