Dakoy
Dakoy

Reputation: 53

uploadfile windows form C# web service

i'm new here,

help me out here please,

i am working with web service and doing upload file.

here's my code for uploading file

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

    }

i can upload file in the same network, but my question is this,

how can i upload file when the two computer is not in the same network?

i've tried changing the

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

to

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

but i'm getting an error 'unable to connect to remote server'

help me out here pls.

Upvotes: 0

Views: 1922

Answers (2)

Ali Dehqan
Ali Dehqan

Reputation: 501

In windows:

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

In server:

[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;
}

Upvotes: 3

Nicolas Tyler
Nicolas Tyler

Reputation: 10552

I think the problem is that you are not actually sending the file with your UploadFile() method, you are just sending the file path. you should be sending the file bytes.

This link is quite usefull: http://www.codeproject.com/Articles/22985/Upload-Any-File-Type-through-a-Web-Service

Upvotes: 0

Related Questions