Null Pointer
Null Pointer

Reputation: 9289

access denied error - c#

I have a text box and a button in a form.i want to save a file into the network path entered in the textbox while clicking the button. i tried the code given below.

 private void button1_Click(object sender, EventArgs e)
    {
        string destinationPath = txtFilePath.Text.ToString();
        string sourceFile = @"c:\1.txt";
        string fileName = Path.GetFileName(sourceFile);
        System.IO.File.Copy(sourceFile, Path.Combine(destinationPath, fileName));

    }

it works fine if the destination provided the permission to change content. If the destination is 'read only' then it gives the error. if the input is \192.168.0.24\aqm , then it shows the error shown below (the path do not have write permission)

Access to the path '\192.168.0.24\aqm\1.txt' is denied.

is there anyway to solve this. i mean, if the destination is read only, then it prompt username and password of that system , if username password entered correct, then save the file to that directory . the user knows the username and password of all the computers in the network. cant give write permission to every system casue of some security reason. thats why i am looking for a method i suggested above

or any other ways?? Hope someone help me

Upvotes: 0

Views: 1371

Answers (3)

Gabe
Gabe

Reputation: 86718

You can ask the user for a username and password, then pass those to a function like WNetAddConnection3 (see http://www.pinvoke.net/default.aspx/mpr/WNetAddConnection3.html for how to call it from C#).

Upvotes: 1

Serkan Hekimoglu
Serkan Hekimoglu

Reputation: 4284

I can suggest you to another way. If it possible, make a Windows Service. Set Service Log On to account which ahve Admin permissions. Make your copy process with Windows Service. I am using this algorithm in one of my projects. It works great, if the service logs in with Admin credentials. The computer have Windows Service with Admin Credentials can easly copy a file on any network machine. For ex, put a System Timer in your service. Let the service checks a path every 5 minutes. If there is a file exist in the given path, take file and copy to network machine by giving path.

Upvotes: 2

jeffo
jeffo

Reputation: 410

I think if the destination is read only there is not much you can do other than notify the user that the file can not be saved because the dest is readonly.

Upvotes: 0

Related Questions