Мне нужно скопировать файл на другой путь, оставив оригинал там, где он есть.
Я также хочу, чтобы иметь возможность переименовывать файл.
Будет ли работать метод FileInfo CopyTo?
Мне нужно скопировать файл на другой путь, оставив оригинал там, где он есть.
Я также хочу, чтобы иметь возможность переименовывать файл.
Будет ли работать метод FileInfo CopyTo?
Посмотрите File.Copy()
Используя File.Copy, вы можете указать новое имя файла как часть строки назначения.
Так что-то вроде
File.Copy(@"c:\test.txt", @"c:\test\foo.txt");
Я попытался скопировать xml файл из одного места в другое. Вот мой код:
public void SaveStockInfoToAnotherFile()
{
string sourcePath = @"C:\inetpub\wwwroot";
string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
string sourceFileName = "startingStock.xml";
string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
Затем я вызвал эту функцию внутри функции timer_elapsed определенного интервала, который, я думаю, вам не нужно видеть. Это сработало. Надеюсь, это поможет.
Да. Он будет работать: FileInfo.CopyTo Method
Используйте этот метод, чтобы разрешить или запретить перезапись существующего файла. Используйте метод CopyTo для предотвращения перезаписывания существующего файла по умолчанию.
Все остальные ответы верны, но поскольку вы запросили FileInfo
, здесь образец:
FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten
Вы также можете использовать File.Copy
для копирования и File.Move
, чтобы переименовать его послесловие.
// Copy the file (specify true or false to overwrite or not overwrite the destination file if it exists.
File.Copy(mySourceFileAndPath, myDestinationFileAndPath, [true | false]);
// EDIT: as "astander" notes correctly, this step is not necessary, as File.Copy can rename already...
// However, this code could be adapted to rename the original file after copying
// Rename the file if the destination file doesn't exist. Throw exception otherwise
//if (!File.Exists(myRenamedDestinationFileAndPath))
// File.Move(myDestinationFileAndPath, myRenamedDestinationFileAndPath);
//else
// throw new IOException("Failed to rename file after copying, because destination file exists!");
ИЗМЕНИТЬ
Прокомментировал код "переименовать", потому что File.Copy
уже может скопировать и переименовать за один шаг, так как в комментариях отмечен знак.
Однако код переименования может быть адаптирован, если OP желает переименовать исходный файл после того, как он был скопирован в новое место.
Файл:: Копия скопирует файл в папку назначения, а File:: Move может перемещать и переименовывать файл.
Это то, что я сделал, чтобы переместить тестовый файл из загрузок на рабочий стол. Я надеюсь, что это будет полезно.
private void button1_Click(object sender, EventArgs e)//Copy files to the desktop
{
string sourcePath = @"C:\Users\UsreName\Downloads";
string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string[] shortcuts = {
"FileCopyTest.txt"};
try
{
listbox1.Items.Add("Starting: Copy shortcuts to dektop.");
for (int i = 0; i < shortcuts.Length; i++)
{
if (shortcuts[i]!= null)
{
File.Copy(Path.Combine(sourcePath, shortcuts[i]), Path.Combine(targetPath, shortcuts[i]), true);
listbox1.Items.Add(shortcuts[i] + " was moved to desktop!");
}
else
{
listbox1.Items.Add("Shortcut " + shortcuts[i] + " Not found!");
}
}
}
catch (Exception ex)
{
listbox1.Items.Add("Unable to Copy file. Error : " + ex);
}
}
string directoryPath = Path.GetDirectoryName(destinationFileName);
// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
File.Copy(sourceFileName, destinationFileName);
Копировать папку Я использую два текстовых поля, чтобы узнать место папки и текстовое поле для текста, чтобы узнать, что папка для копирования, и это код
MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
if (Fromtb.Text=="")
{
MessageBox.Show("Ples You Should Write All Text Box");
Fromtb.Select();
return;
}
else if (Nametb.Text == "")
{
MessageBox.Show("Ples You Should Write The Third Text Box");
Nametb.Select();
return;
}
else if (Totb.Text == "")
{
MessageBox.Show("Ples You Should Write The Second Text Box");
Totb.Select();
return;
}
string fileName = Nametb.Text;
string sourcePath = @"" + Fromtb.Text;
string targetPath = @"" + Totb.Text;
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
//when The User Write The New Folder It Will Create
MessageBox.Show("The File is Create in "+" "+Totb.Text);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
MessageBox.Show("The File is copy To " + Totb.Text);
}