C#-move files from folders
Source and destination path must have identical roots.
Move will not work across volumes.
You can’t move directories across the volumes. You need to write your own logic to perform
directory move across the volumes. Following example will end up with Exception of type
explained above.
using System;
using System.IO;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Directory.Move(@"C:\MyDirectory",@"D:\MyDirectory");
}
}
}
Move Directory across the volume
First check wheather dirctory exists at destination or not. If it doesn’t exists create new directory
at destination and move all files to destination.
using System;
using System.IO;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string source = @"C:\MyDirectory";
string destination = @"D:\MyDirectory";
MoveDirectory(source, destination);
}
static void MoveDirectory(string source, string destination)
{
if( Directory.GetDirectoryRoot(source) != Directory.GetDirectoryRoot(destination))
{
CreateDirectory(destination);
string []sourceFiles = Directory.GetFiles(source);
CopyFiles(sourceFiles,destination);
Directory.Delete(source);
}
}
static void CopyFiles(string []sourceFiles, string destination)
{
foreach (string file in sourceFiles)
{
FileInfo f = new FileInfo(file);
f.CopyTo(destination+ @"\" + f.Name);
f.Delete();
}
}
static void CreateDirectory(string destination)
{
if (!Directory.Exists(destination))
{
Directory.CreateDirectory(destination);
}
}
}
}
Description:
The instance of FileInfo provides Delete method which deletes the actual file
referred by instance.
FileInfo instance method CopyTo copies the file from source to destination.
The destination should be the name of fully qualified path name.
Note: You need to modify above code to fulfill your requirement.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5