Search code examples
c#wpfwinformsmove.net

Auto creating folders when using System.IO.File.Move


I'm updating an old winforms app which moves files to new locations using regex and System.IO.File.Move

Under windows 7, the old app worked fine. If a folder didn't exist, File.Move would create it

System.IO.File.Move("c:\stuff\a.txt","c:\stuff\a\file.txt");
System.IO.File.Move("c:\stuff\b.txt","c:\stuff\b\file.txt");
System.IO.File.Move("c:\stuff\c.txt","c:\stuff\c\file.txt");

However, under Windows 8 it seems that I have to manually create each folder in the path first. I get an error if I try and move to a folder that doesn't exist yet. Anyone know a way around this? I'd rather not have to create each folder

NOTE: The new, updated app is on WPF rather than winforms. Not sure if that's relevant


Solution

  • Before you File.Move() you could do:

    new System.IO.FileInfo("c:\\stuff\\a\\file.txt").Directory.Create();
    

    The above will create the "stuff" and "a" folders if they don't exist.