开发者

ASP.NET file transfer from local machine to another machine

开发者_运维技巧I basically want to transfer a file from the client to the file storage server without actual login to the server so that the client cannot access the storage location on the server directly. I can do this only if i manually login to the storage server through windows login. I dont want to do that. This is a Web-Based Application.

Using the link below, I wrote a code for my application. I am not able to get it right though, Please refer the link and help me ot with it...

Uploading files to file server using webclient class


The following is my code:-

protected void Button1_Click(object sender, EventArgs e) 
{ 

    filePath = FileUpload1.FileName;     
    try 
    { 
        WebClient client = new WebClient(); 

        NetworkCredential nc = new NetworkCredential(uName, password); 

        Uri addy = new Uri("\\\\192.168.1.3\\upload\\"); 
        client.Credentials = nc; 
        byte[] arrReturn = client.UploadFile(addy, filePath); 

        Console.WriteLine(arrReturn.ToString()); 
    } 
    catch (Exception ex) 
    { 
        Console.WriteLine(ex.Message); 
    } 

} 

The following line doesn't execute...

byte[] arrReturn = client.UploadFile(addy, filePath); 

This is the error I get:

An exception occurred during a WebClient request


Ah, it seems (and with good reason), the FileUpload can only save files to the web server and its drives. So my first thought won't work.

But: if you have the necessary permissions, couldn't you just save the file that you get in the FileUpload to that UNC path using standard System.IO calls?? Something like :

protected void Button1_Click(object sender, EventArgs e) 
{ 
    try 
    { 
        string completeFileName = 
           Path.Combine(@"\\192.168.1.3\upload", FileUpload1.FileName); 

        BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream);

        FileStream fstm = new FileStream(completeFileName, FileMode.Create, FileAccess.ReadWrite);
        BinaryWriter bw = new BinaryWriter(fstm);

        byte[] buffer = br.ReadBytes(FileUpload1.PostedFile.ContentLength);
        br.Close();

        bw.Write(buffer);
        bw.Flush();
        bw.Close();
    } 
    catch (Exception ex) 
    { 
        Console.WriteLine(ex.Message); 
    } 
} 

If you expect very large files to be uploaded, you might want to transfer the data from the BinaryReader to the BinaryWriter in chunks - instead of allocating just a single buffer - but that's just an implementation detail, really.


I had the same issue a few days ago, I solved it by creating a user on the Web server and on the storage server with the same user name and password, I then impersonated the user in the web.config file.

NB: The user should have RW permissions in the directory where you want to store the files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜