Is there no .NET library call for copying a file to a directory? All library calls I found (eg File.Copy()
or FileInfo.CopyTo()
) do only support copying a file to another fully specified file .
string file = "C:\Dir\ect\ory\file.txt";
string dir = "C:\Other\Directory";
File.Copy(file, dir); // does not work, requires filename
Is there a library call? If no, what's the best way to write my own utility, do I really have to use Path.GetFileName()
?
do I really have to use Path.GetFileName()?
Exactly:
string destination = Path.Combine(dir, Path.GetFileName(file));
Directory.CreateDirectory(dir);
File.Copy(file, destination);
Try this example
public class SimpleFileCopy
{
static void Main()
{
string fileName = "test.txt";
string sourcePath = @"C:\Users\Public\TestFolder";
string targetPath = @"C:\Users\Public\TestFolder\SubDir";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.