使用C#表单应用程序尝试连接远程服务器

3
我想做的是连接远程服务器并读取文本文件,然后在控制台显示它。远程服务器需要用户名和密码才能访问。我想问您们这样做的最佳方法是什么?
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());
    }
}

}


什么身份验证类型?基本认证?表单? - The Mask
1个回答

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();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接