none
File copy to c# RRS feed

Answers

  • Hi Ahron321,

    nice to hear that. It would be great if you mark the code as answer, that worked for you.

    Greetings, Chris

    • Marked as answer by Ahron321 Thursday, November 8, 2018 9:11 PM
    Wednesday, November 7, 2018 9:06 PM

All replies

  • this is posibale to copy a folder with files in it?

    What do you mean by that? It is possible to copy/create files and folders using c#.

    Please give us some more informations about what you are trying to achieve...

    Greetings, Chris

    Tuesday, October 23, 2018 1:17 PM
  • There are three solutions on the following page.

    https://stackoverflow.com/questions/58744/copy-the-entire-contents-of-a-directory-in-c-sharp


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, October 23, 2018 1:30 PM
    Moderator
  • I mean i create a folder and in the folder i have stuff like lol.txt and more and i want to copy that folder copy not more copy and paste it like in D: drive ok somthing
    Tuesday, October 23, 2018 1:35 PM
  • but there are so many codes and i dont knmow how use them
    Tuesday, October 23, 2018 5:27 PM
  • Ok, you want to copy a folder containing all files and subfolders?
    Tuesday, October 23, 2018 6:01 PM
  • .NET does not have directory copy function. It does have a directory move which will copy across volumes but that is rarely what you want. Fortunately though in the Common IO Tasks documentation is an example function that copies a directory (and optionally its children). Refer to this sample on how to do it.

    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, October 23, 2018 6:06 PM
    Moderator
  • Hi,

    you can copy a folder including all files and subfolders like this:

            public class FolderCopier
            {
                public static void CopyFolder(string path, string newpath)
                {
                    var d = new DirectoryInfo(path);
                    var files = d.GetFiles();
                    var directories = d.GetDirectories();
                    newpath = newpath.EndsWith("\\") || newpath.EndsWith("/") ? $"{newpath}{d.Name}\\" : $"{newpath}\\{d.Name}\\";
                    Directory.CreateDirectory(newpath);
                    foreach (var file in files)
                    {
                        file.CopyTo(newpath + file.Name);
                    }
                    foreach (var directory in directories)
                    {
                        CopyFolder(directory.FullName, newpath);
                    }
                }
            }
    Do you copy?

    Greetings, Chris

    Tuesday, October 23, 2018 7:21 PM
  • You can use SHFileOperation =>

    string sSource = @"E:\test1";
    string sDest = @"E:\test2";
    var fos = new SHFILEOPSTRUCT
    {
        wFunc = FO.FO_COPY,
        pFrom = sSource + '\0',
        pTo = sDest + '\0',
        fFlags = FILEOP_FLAGS.FOF_ALLOWUNDO
    };
    int nReturn = SHFileOperation(ref fos);
    if (nReturn != 0)
    {                  
      throw new Win32Exception(nReturn);
    }

    Declarations :

            public enum FO : int
            {
                FO_MOVE = 0x0001,
                FO_COPY = 0x0002,
                FO_DELETE = 0x0003,
                FO_RENAME = 0x0004
            }
    
            [Flags]
            public enum FILEOP_FLAGS : uint
            {
                FOF_MULTIDESTFILES = 0x0001,
                FOF_CONFIRMMOUSE = 0x0002,
                FOF_SILENT = 0x0004,  // don't create progress/report
                FOF_RENAMEONCOLLISION = 0x0008,
                FOF_NOCONFIRMATION = 0x0010,  // Don't prompt the user.
                FOF_WANTMAPPINGHANDLE = 0x0020,  // Fill in SHFILEOPSTRUCT.hNameMappings
                                                 // Must be freed using SHFreeNameMappings
                FOF_ALLOWUNDO = 0x0040,
                FOF_FILESONLY = 0x0080,  // on *.*, do only files
                FOF_SIMPLEPROGRESS = 0x0100,  // means don't show names of files
                FOF_NOCONFIRMMKDIR = 0x0200,  // don't confirm making any needed dirs
                FOF_NOERRORUI = 0x0400,  // don't put up error UI
                FOF_NOCOPYSECURITYATTRIBS = 0x0800,  // dont copy NT file Security Attributes
                FOF_NORECURSION = 0x1000,  // don't recurse into directories.
                FOF_NO_CONNECTED_ELEMENTS = 0x2000,  // don't operate on connected file elements.
                FOF_WANTNUKEWARNING = 0x4000,  // during delete operation, warn if nuking instead of recycling (partially overrides FOF_NOCONFIRMATION)
                FOF_NORECURSEREPARSE = 0x8000,  // treat reparse points as objects, not containers
    
                FOFX_NOSKIPJUNCTIONS = 0x00010000,  // Don't avoid binding to junctions (like Task folder, Recycle-Bin)
                FOFX_PREFERHARDLINK = 0x00020000,  // Create hard link if possible
                FOFX_SHOWELEVATIONPROMPT = 0x00040000,  // Show elevation prompts when error UI is disabled (use with FOF_NOERRORUI)
                FOFX_EARLYFAILURE = 0x00100000,  // Fail operation as soon as a single error occurs rather than trying to process other items (applies only when using FOF_NOERRORUI)
                FOFX_PRESERVEFILEEXTENSIONS = 0x00200000,  // Rename collisions preserve file extns (use with FOF_RENAMEONCOLLISION)
                FOFX_KEEPNEWERFILE = 0x00400000,  // Keep newer file on naming conflicts
                FOFX_NOCOPYHOOKS = 0x00800000,  // Don't use copy hooks
                FOFX_NOMINIMIZEBOX = 0x01000000,  // Don't allow minimizing the progress dialog
                FOFX_MOVEACLSACROSSVOLUMES = 0x02000000,  // Copy security information when performing a cross-volume move operation
                FOFX_DONTDISPLAYSOURCEPATH = 0x04000000,  // Don't display the path of source file in progress dialog
                FOFX_DONTDISPLAYDESTPATH = 0x08000000,  // Don't display the path of destination file in progress dialog
            }  
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
            public struct SHFILEOPSTRUCT
            {
                public IntPtr hwnd;
                [MarshalAs(UnmanagedType.U4)]
                public FO wFunc;
                public string pFrom;
                public string pTo;
                public FILEOP_FLAGS fFlags;
                [MarshalAs(UnmanagedType.Bool)]
                public bool fAnyOperationsAborted;
                public IntPtr hNameMappings;
                public string lpszProgressTitle;
            }
    
            [DllImport("Shell32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "SHFileOperationW")]
            public static extern int SHFileOperation(ref SHFILEOPSTRUCT lpFileOp);

    Tuesday, October 23, 2018 7:22 PM
  • I am doing that code in loop and working but when the file alredy exist so it give me an error: http://prntscr.com/l9m46y
    Tuesday, October 23, 2018 8:18 PM
  •         public class FolderCopier
            {
                public static void CopyFolder(string path, string newpath)
                {
                    var d = new DirectoryInfo(path);
                    var files = d.GetFiles();
                    var directories = d.GetDirectories();
                    newpath = newpath.EndsWith("\\") || newpath.EndsWith("/") ? $"{newpath}{d.Name}\\" : $"{newpath}\\{d.Name}\\";
                    Directory.CreateDirectory(newpath);
                    foreach (var file in files)
                    {
                        try
                        {
                            file.CopyTo(newpath + file.Name);
                        }
                        catch (Exception e)
                        {
    
                        }
                    }
                    foreach (var directory in directories)
                    {
                            CopyFolder(directory.FullName, newpath);
                    }
                }
            }
    PS: This is not good. Using try catch to control workflow is a bad practice...


    • Edited by DerChris88 Tuesday, October 23, 2018 8:30 PM
    Tuesday, October 23, 2018 8:23 PM
  • How do i use that?
    Tuesday, October 23, 2018 8:24 PM
  •         public class FolderCopier
            {
                public static void CopyFolder(string path, string newpath)
                {
                    var d = new DirectoryInfo(path);
                    var files = d.GetFiles();
                    var directories = d.GetDirectories();
                    newpath = newpath.EndsWith("\\") || newpath.EndsWith("/") ? $"{newpath}{d.Name}\\" : $"{newpath}\\{d.Name}\\";
                    Directory.CreateDirectory(newpath);
                    foreach (var file in files)
                    {
                        if(!File.Exists(newpath + file.Name))
                            file.CopyTo(newpath + file.Name);
                    }
                    foreach (var directory in directories)
                    {
                        CopyFolder(directory.FullName, newpath);
                    }
                }
            }

    Tuesday, October 23, 2018 8:25 PM
  • or do you want to overwrite the files?

            public class FolderCopier
            {
                public static void CopyFolder(string path, string newpath)
                {
                    var d = new DirectoryInfo(path);
                    var files = d.GetFiles();
                    var directories = d.GetDirectories();
                    newpath = newpath.EndsWith("\\") || newpath.EndsWith("/") ? $"{newpath}{d.Name}\\" : $"{newpath}\\{d.Name}\\";
                    Directory.CreateDirectory(newpath);
                    foreach (var file in files)
                    {
                        file.CopyTo(newpath + file.Name, true);
                    }
                    foreach (var directory in directories)
                    {
                        CopyFolder(directory.FullName, newpath);
                    }
                }
            }


    Do you see the overload of CopyTo? Set the second parameter to true to overwrite all files:

    file.CopyTo(newpath + file.Name, true);


    • Edited by DerChris88 Tuesday, October 23, 2018 8:33 PM
    Tuesday, October 23, 2018 8:27 PM
  • Hello dude?! i do i use that
    Tuesday, October 23, 2018 8:28 PM
  • No jsut copy the folder with all the files in it
    Tuesday, October 23, 2018 8:30 PM
  • So it depends on what do you want to do. First contains a bad practice, do not use(I just left it there to show: do not use this ;D). Second is skipping existing files, and third is overwriting all files in destination folder.

    • Edited by DerChris88 Tuesday, October 23, 2018 8:38 PM
    Tuesday, October 23, 2018 8:36 PM
  • So the differce between the first and the second is, the first will just ignore exceptions, like file already exists, on CopyTo. The second is checking if the file does not exists and copies it. So if you have for example another exception like your hard disk is full, the first code will continue. The second will throw an exception showing you the error.

    Yes, It's possible to catch different exceptions, but it should still be used for error handling and not for flow...

    So, do not use the first example ;)

    Tuesday, October 23, 2018 8:53 PM
  • you can use it like this:

    FolderCopier.CopyFolder(@"C:\testcopy\1", @"C:\testcopy\2");
    Copies directory "1" and all files, subdirectories to "2". So later you have "c:\testcopy\2\1\..."

    Greetings, Chris


    • Edited by DerChris88 Tuesday, October 23, 2018 9:01 PM
    Tuesday, October 23, 2018 8:56 PM
  • Did you test it?
    Thursday, October 25, 2018 9:01 PM
  • yes working
    Wednesday, November 7, 2018 6:29 PM
  • Hi Ahron321,

    nice to hear that. It would be great if you mark the code as answer, that worked for you.

    Greetings, Chris

    • Marked as answer by Ahron321 Thursday, November 8, 2018 9:11 PM
    Wednesday, November 7, 2018 9:06 PM