How to copy a file from the network to my computer using C #?

7

I have a desktop application that needs to copy media files from a server, videos and images. The server is on the same network as the terminal on which the program is installed. The problem is that this terminal will not be logged in with username and password on the network, I will have to pass a user and a password for it to be able to work with the files, however I did not find how to do it. p>

My implementation below works perfectly on my PC, where I am logged in with a network user and my password, it will search the files on the server and put them in the path on my computer. But when he squeezes it into the terminal that should be running the videos and images he says that the system is not allowed access.

if (System.IO.Directory.Exists(sourcePath))
            {
                string[] directoryes = System.IO.Directory.GetDirectories(sourcePath, "*", System.IO.SearchOption.AllDirectories);

                foreach (string directoriePath in directoryes)
                {
                    string[] files = System.IO.Directory.GetFiles(directoriePath);

                    if (files.Count() != 0)
                    {
                        // Copy the files and overwrite destination files if they already exist.
                        foreach (string s in files)
                        {
                            // Use static Path methods to extract only the file name from the path.
                            string fileName = System.IO.Path.GetFileName(s);
                            string destFile = System.IO.Path.Combine(targetPath, fileName);
                            System.IO.File.Copy(s, destFile, true);
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("Source path does not exist!");
            }

How can I first log in with username and password on the server and fetch these files?

    
asked by anonymous 24.05.2016 / 21:44

1 answer

5
One solution is to use the class Impersonator available in CodeProject .

You also have good answers (accept and voted) in the SO . They used WNetAddConnection2 of the Windows API to achieve this. It seems to be the solution most followed, with variations of implementations. Another question has alternative implementations .

    
24.05.2016 / 22:19