-6

I have a problem about copying an exe file in my visual studio project folder to my computer desktop or somewhere else in my computer by using C#.

How can I do that?

Felix D.
  • 4,811
  • 8
  • 38
  • 72
Barsblue
  • 109
  • 1
  • 15
  • 2
    **I have a problem about copying [...]** - what exactly **is** that **problem** ? – Felix D. Feb 06 '18 at 07:24
  • 2
    In general you can use [`File.Copy`](https://msdn.microsoft.com/en-us/library/9706cfs5(v=vs.110).aspx) – Felix D. Feb 06 '18 at 07:25
  • 3
    In case you are wondering why nobody knows what you are asking, here are some ways to interpret your question: *"How can I copy a file?"*, *"How can I get the path to my desktop?"*, *"It works with other directories but here I get an exception"*, etc. Include your code ([mcve]) and clarify your question. – Manfred Radlwimmer Feb 06 '18 at 07:27
  • 1
    One more thing to keep in mind: On StackOverflow you get responses *very* fast. If you ask a question, stick around at least for the first 30 minutes or so. Otherwise you might find a lot of these: http://idownvotedbecau.se/beingunresponsive – Manfred Radlwimmer Feb 06 '18 at 07:35

2 Answers2

1

This answer is directly from Microsoft website, please check the reference link.

The following example shows how to copy files and directories.

// Simple synchronous file copy operations with no user interface.
// To run this sample, first create the following directories and files:
// C:\Users\Public\TestFolder
// C:\Users\Public\TestFolder\test.txt
// C:\Users\Public\TestFolder\SubDir\test.txt
public class SimpleFileCopy
{
    static void Main()
    {
        string fileName = "test.txt";
        string sourcePath = @"C:\Users\Public\TestFolder";
        string targetPath =  @"C:\Users\Public\TestFolder\SubDir";

        // Use Path class to manipulate file and directory paths.
        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
        string destFile = System.IO.Path.Combine(targetPath, fileName);

        // To copy a folder's contents to a new location:
        // Create a new target folder, if necessary.
        if (!System.IO.Directory.Exists(targetPath))
        {
            System.IO.Directory.CreateDirectory(targetPath);
        }

        // To copy a file to another location and 
        // overwrite the destination file if it already exists.
        System.IO.File.Copy(sourceFile, destFile, true);

        // To copy all the files in one directory to another directory.
        // Get the files in the source folder. (To recursively iterate through
        // all subfolders under the current directory, see
        // "How to: Iterate Through a Directory Tree.")
        // Note: Check for target path was performed previously
        //       in this code example.
        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);

            // 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.
                fileName = System.IO.Path.GetFileName(s);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile, true);
            }
        }
        else
        {
            Console.WriteLine("Source path does not exist!");
        }

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

Reference: Microsoft (06-02-2018).

BH7
  • 204
  • 2
  • 8
1

Get your working directory:

string appDir = AppDomain.CurrentDomain.BaseDirectory;

Specify your target directory:

string targetDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

Get the file(s) you want using Directory.GetFiles:

FileInfo[] files = new DirectoryInfo(appDir).GetFiles(*.*, SearchOption.TopDirectoryOnly);

Copy your files:

try
{
    foreach(FileInfo file in files)
    {
        File.Copy(file.FullName, Path.Combine(targetDir, file.Name), true);
    }
}
catch (Exception ex)
{
    //Handle DirectoryAccess errors and others
}
Felix D.
  • 4,811
  • 8
  • 38
  • 72
  • You could also add `Environment.GetFolderPath(Environment.SpecialFolder.Desktop));` as an alternative to `ExpandEnvironmentVariables` (Desktop paths don't always follow that pattern) or at least use `%USERPROFILE%` instead. – Manfred Radlwimmer Feb 06 '18 at 07:37
  • 1
    @ManfredRadlwimmer I just did that :D noticed it myself :P – Felix D. Feb 06 '18 at 07:38
  • Just saw it ^^. I'd still swap out that `%USERNAME%` though. – Manfred Radlwimmer Feb 06 '18 at 07:39
  • @ManfredRadlwimmer Yeah I guess using `Environement` is more "clean". Do you know by any change the difference between `Environment.SpecialFolder.Desktop` and `Environment.SpecialFolder.DesktopDirectory` ? When debugging there is not difference at all .. – Felix D. Feb 06 '18 at 07:41
  • Not 100% sure in what kind of special cases it's relevant, but apparently [this](https://stackoverflow.com/questions/5612571/whats-the-difference-between-specialfolder-desktop-and-specialfolder-desktopdir) is the answer (sounds like a legacy thing to be honest) – Manfred Radlwimmer Feb 06 '18 at 07:42
  • I guess to be safe you should use `DesktopDirectory` I will fix that in my answer – Felix D. Feb 06 '18 at 07:44
  • @FelixD. My file's name is "mariadb-10.1.21-winx64.msi".What must be added to the point indicated by the dot at " FileInfo[] files = new DirectoryInfo(appDir).GetFiles(*.*, SearchOption.TopDirectoryOnly);" – Barsblue Feb 06 '18 at 08:02
  • @Barsblue you can use `"*.msi"` to match all `msi` files or specify the full name (`[...].GetFiles("mariadb-10.1.21-winx64.msi")`) [`reference`](https://msdn.microsoft.com/en-us/library/ms143327(v=vs.110).aspx) – Felix D. Feb 06 '18 at 08:07