nlstack01
nlstack01

Reputation: 839

Move Directory Into Current Directory C#

I want to do something simple. Take the contents of folder A and move the files and folders into a folder within folder A. Then make folder A hidden.

The code below is getting an exception of hiddenTarget is not found.

Directory.Create(hiddenTarget) is not helping

There must be a simple way to do this. Currently I am attempting to make a temp directory. Put all files from the current directory in it. Then Move the temp directory to the current directory. Then make the current directory hidden.

Here is the code in issue..

string tempFolder = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), "tempTarget");
//Directory.CreateDirectory(tempFolder);

Directory.Move(currentTarget, tempFolder);

string hiddenTarget = Path.Combine(currentTarget, @".bak");
//Directory.CreateDirectory(hiddenTarget);

Directory.Move(tempFolder, hiddenTarget);

DirectoryInfo di = new DirectoryInfo(currentTarget);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;

Upvotes: 0

Views: 352

Answers (1)

580
580

Reputation: 480

So you have two issues here first is that your hidden target cannot start with a '.' because as pointed out in the comments that is illegal in NTFS.

enter image description here

As you can see File Explorer doesn't like this syntax.

As pointed out by @Dour High Arch here is the link to the relevant information: Naming Files, Paths, and Namespaces


Your next issue is that the move is destroying the original directory structure. Therefore, your steps need to be as follows:

1) Move to a temporary directory to avoid any issues with the two processes (file system & your process) fighting for access.

2) Due to the fact that the Directory.Move in step #1 destroyed the original source directory. Recreate the destroyed source folder.

3) Then move into the desired nested folder. This move operation will automatically create the desired sub-directory. Step #2 is required because for whatever reason I'm still looking into Directory.Move cannot automatically create the structure without the source directory already existing.

        string currentTarget = @"C:\A";
        string hiddenTarget = @"C:\A\Subfolder";

        string tempTarget = @"C:\Temp";

        Directory.Move(currentTarget, tempTarget);
        Directory.CreateDirectory(currentTarget);
        Directory.Move(tempTarget, hiddenTarget);

        DirectoryInfo di = new DirectoryInfo(currentTarget);
        di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;

Update

From an engineering perspective you really should be performing copies if you really care about the data being moved. It may be slower, but will help prevent any horrible things from happening to the data. You should check whether or not these directories exist first before creating them. Exception handling within this example is at a minimum as well. What I'm really trying to stress here is handle the data that is being moved with care!

    static void Main(string[] args)
    {
        string sourceDir = @"C:\Src";
        string tempDir = @"C:\Temp";
        string destDir = Path.Combine(sourceDir, "Dest");

        // Could optionally check to verify that the temp directory already exists here and destroy it if it does.
        // Alternatively, pick a really unique name for the temp directory by using a GUID, Thread Id or something of that nature.
        // That way you can be sure it does not already exist.

        // Copy to temp, then destroy source files.
        CopyDirectory(sourceDir, tempDir);
        Directory.Delete(sourceDir, true);

        // Copy to dest
        CopyDirectory(tempDir, destDir);

        // Hide the source directory.
        DirectoryInfo di = new DirectoryInfo(sourceDir);
        di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;

        // Clean up the temp directory that way copies of the files aren't sitting around.
        // NOTE: Be sure to do this last as if something goes wrong with the move the temp directory will still exist.
        Directory.Delete(tempDir, true);

    }

    /// <summary>
    /// Recursively copies all subdirectories.
    /// </summary>
    /// <param name="sourceDir">The source directory from which to copy.</param>
    /// <param name="destDir">The destination directory to copy content to.</param>
    static void CopyDirectory(string sourceDir, string destDir)
    {
        var sourceDirInfo = new DirectoryInfo(sourceDir);
        if (!sourceDirInfo.Exists)
        {
            throw new DirectoryNotFoundException($"Source directory does not exist or could not be found: '{sourceDir}'");
        }

        // If the destination directory doesn't exist, create it.
        if (!Directory.Exists(destDir))
        {
            Directory.CreateDirectory(destDir);
        }

        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = sourceDirInfo.GetFiles();
        foreach (FileInfo file in files)
        {
            string tempPath = Path.Combine(destDir, file.Name);
            file.CopyTo(tempPath, false);
        }

        // Copy subdirectories
        DirectoryInfo[] subDirs = sourceDirInfo.GetDirectories();
        foreach (DirectoryInfo subdir in subDirs)
        {
            string tempPath = Path.Combine(destDir, subdir.Name);
            CopyDirectory(subdir.FullName, tempPath);
        }
    }

Here are a few more links regarding the above.

MSDN - How to: Copy Directories

Stack Overflow - How to copy the entire contents of directory in C#?

Upvotes: 2

Related Questions