Search code examples
c#replacecopyrename

(C#) Copying User Selected File To AppData Folder


Okay, so. I'm going to try to explain this as best as I can.

I have been working on a program, obviously. Basically, the user selects one file hits the "Replace" button and it replaces the files in a AppData folder.

Well, I got how to make an AppData folder for my program. Basically, what I would like to do is first off take the selected file (that's through the open file dialog) and copy to the AppData that I created for one. Then I need to rename the file and copy the file to the other folder.

I've been looking and can't seem to find what I need...which sucks.

EDIT: My second question. Say the user chooses "myfile.txt" there's a folder in the AppData at ".../Roaming/thefiles/file.txt"

I need to rename and replace that "file.txt", but I can not figure out how to move to that directory since everyone's username is different.


Solution

  • First of all you dont need to create a folder in AppData it will be readily available.

    File.Copy(sourcepath,destinationpath); can be used for this purpose
    

    http://msdn.microsoft.com/en-us/library/cc148994.aspx check this out.

    use Application.UserAppDataPath or Application.CommonAppDataPath to access your program's app data folder.

    You can call:

    File.Copy(sourcepath,Path.Combine(Application.UserAppDataPath,"yourfile.ext"));
    

    Edit

    I understand you mean logged in user of the system:

    using (OpenFileDialog fd = new OpenFileDialog())
    {
        if (fd.ShowDialog() == DialogResult.OK)
        {
            string fullFileName = fd.FileName;
            string fileNameWithExt = Path.GetFileName(fullFileName);
            string destPath = Path.Combine(Application.UserAppDataPath, fileNameWithExt);
            File.Copy(fd.FileName, destPath);
        }
    }
    

    the above code would copy the selected file to AppData path of your Program that belongs to logged in user, ex: if you logged in as user1 to windows this will be copied under user1's AppData.

    Edit2

    If am not mistaken then Application.UserAppDataPath will always give the path of current logged user of windows, so without worrying of losing other user's data you can safely move the file inside that Directory.