正在尝试使用C#窗体应用程序连接到远程服务器

本文关键字:连接 应用程序 服务器 窗体 | 更新日期: 2023-09-27 18:21:29

我要做的是连接到远程服务器,读取一个文本文件,然后将其显示在控制台中。远程服务器需要用户名和密码才能访问。我想问你们最好的方法是什么。

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

}

正在尝试使用C#窗体应用程序连接到远程服务器

不确定这是否是最好的方法,但我已经做了类似的事情,映射了一个驱动器,然后使用映射的驱动器号访问文件:

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