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

Question:

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 will be installed. The problem is, that this terminal will not be logged in with a username and password on the network, I will have to pass a username and password to it to be able to work with the files, but I didn't find how to do that.

My implementation below works perfectly on my PC, where I am logged in with the network username and my password, it fetches the files from the server and puts them in the path on my computer. But when I run it in the terminal that should be running the videos and images it says that the system does not have access permission.

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 log in first with username and password on the server and search for these files?

Answer:

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

It also has good answers (the accepted and most upvoted one) on SO . They used WNetAddConnection2 from the Windows API to achieve this. It seems to be the most followed solution, with variations of implementations. Another question has alternative implementations .

Scroll to Top