0

我是新来的,

请帮帮我,

我正在使用网络服务并上传文件。

这是我上传文件的代码

   private void Button_Click(object sender, RoutedEventArgs e)
    {
        testServiceClient = new TestServiceClient();

        var uploadFile = "C:\\Computer1\\Sample.csv";

        try
        {
            var dir = @"\\Computer2\UploadedFile\";
            string myUploadPath = dir;
            var myFileName = Path.GetFileName(uploadFile);

            var client = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials };

            client.UploadFile(myUploadPath + myFileName, "PUT", uploadFile);
            client.Dispose();

            MessageBox.Show("ok");

            testServiceClient.Close();
        }
        catch (Exception ex)
        {
            ex.ToString();
        }

    }

我可以在同一个网络中上传文件,但我的问题是,

当两台计算机不在同一个网络中时,我如何上传文件?

我试过改变

var dir = @"\\Computer2\UploadedFile\"; 

var dir = @"https://Computer2/UploadedFile/";

但我收到错误“无法连接到远程服务器”

请帮帮我。

4

2 回答 2

3

在窗口中:

private void uploadButton_Click(object sender, EventArgs e)
{
    var openFileDialog = new OpenFileDialog();
    var dialogResult = openFileDialog.ShowDialog();    
    if (dialogResult != DialogResult.OK) return;              
    Upload(openFileDialog.FileName);
}

private void Upload(string fileName)
{
    var client = new WebClient();
    var uri = new Uri("https://Computer2/UploadedFile/");  
    try
    {
        client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
        var data = System.IO.File.ReadAllBytes(fileName);
        client.UploadDataAsync(uri, data);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

在服务器中:

[HttpPost]
public async Task<object> UploadedFile()
{
    var file = await Request.Content.ReadAsByteArrayAsync();
    var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
    var filePath = "/upload/files/";
    try
    {
        File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);           
    }
    catch (Exception ex)
    {
        // ignored
    }

    return null;
}
于 2016-10-24T13:07:35.043 回答
0

我认为问题在于您实际上并没有使用您的UploadFile()方法发送文件,您只是发送文件路径。你应该发送文件字节。

这个链接非常有用: http: //www.codeproject.com/Articles/22985/Upload-Any-File-Type-through-a-Web-Service

于 2013-09-09T06:38:00.170 回答