Usuário com melhor resposta
Erro ao copiar e colar c#

Pergunta
-
Eu estou usando uma função para copiar e colar os arquivos e pasta porem estou tendo dois problemas:
1) Ao copiar um arquivo de uma pasta(pasta1) para outras(pasta2), a função copia todos os arquivos da pasta1 para pasta2;
2) Ao copiar uma pasta1 para a pasta2, ele informa que não pode criar a pasta porque, já existe um arquivo ou pasta com o mesmo nome na pasta2.
segue as código da função:
public void CopiarColar(string fileName, string sourcePath, string targetPath) { File.SetAttributes(sourcePath, FileAttributes.Normal); File.SetAttributes(targetPath, FileAttributes.Normal); //string fileName = "test.txt"; //string sourcePath = @"C:\Users\Public\TestFolder"; //string targetPath = @"C:\Users\Public\TestFolder\SubDir"; // Use Path class to manipulate file and directory paths. string sourceFile = Path.Combine(sourcePath, fileName); string destFile = Path.Combine(targetPath, fileName); // To copy a folder's contents to a new location: // Create a new target folder, if necessary. if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); //.Attributes=FileAttributes.Normal; } if (Directory.Exists(sourceFile)) { if (!Directory.Exists(destFile)) { Directory.CreateDirectory(destFile);//.Attributes = FileAttributes.Normal; } } // To copy a file to another location and // overwrite the destination file if it already exists. if (File.Exists(sourceFile)) { File.SetAttributes(sourceFile, FileAttributes.Normal); File.Copy(sourceFile, destFile, true); } // To copy all the files in one directory to another directory. // Get the files in the source folder. (To recursively iterate through // all subfolders under the current directory, see // "How to: Iterate Through a Directory Tree.") // Note: Check for target path was performed previously // in this code example. if (Directory.Exists(destFile) && Directory.Exists(sourcePath)) { string[] files = Directory.GetFiles(sourcePath); // Copy the files and overwrite destination files if they already exist. foreach (string s in files) { // Use static Path methods to extract only the file name from the path. fileName = Path.GetFileName(s); destFile = Path.Combine(targetPath, fileName); File.Copy(s, destFile, true); } } }
Código toolStripMenuColar_Click
private void toolStripMenuColar_Click(object sender, EventArgs e) { destino = treeView1.SelectedNode.FullPath; if (treeView1.SelectedNode.FullPath.Contains("salvar")) { destino = treeView1.SelectedNode.FullPath.Replace("salvar", @"\\dados\salvar"); } MessageBox.Show(arquivoasercopiado + "," + origem + "," + destino); if (Directory.Exists(origem + @"\" + arquivoasercopiado) || File.Exists(origem + @"\" + arquivoasercopiado) || destino !="") { Comandos comando = new Comandos(); if (recortar == 1) { comando.CopiarColar(arquivoasercopiado, origem, destino); comando.Excluir(origem+@"\" + arquivoasercopiado); recortar = 0; toolStripMenuColar.Enabled = false; this.treeView1_AfterSelect(treeView1, null); } else { comando.CopiarColar(arquivoasercopiado, origem, destino); this.treeView1_AfterSelect(treeView1, null); } } else { MessageBox.Show("Arquivo não encontrado."); } }
Segue as imagens:
Respostas
-
Não se o que aconteceu, sem modificar nada, quando fui testar hoje boa parte dos erros tinham sumido, o que me permitiu corrigir o resto.
o arquivo ficou assim
public void CopiarColar(string fileName, string sourcePath, string targetPath) { File.SetAttributes(sourcePath, FileAttributes.Normal); File.SetAttributes(targetPath, FileAttributes.Normal); //string fileName = "test.txt"; //string sourcePath = @"C:\Users\Public\TestFolder"; //string targetPath = @"C:\Users\Public\TestFolder\SubDir"; // Use Path class to manipulate file and directory paths. string sourceFile = Path.Combine(sourcePath, fileName); string destFile = Path.Combine(targetPath, fileName); // To copy a folder's contents to a new location: // Create a new target folder, if necessary. if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); //.Attributes=FileAttributes.Normal; } if (Directory.Exists(sourceFile)) { if (!Directory.Exists(destFile)) { Directory.CreateDirectory(destFile);//.Attributes = FileAttributes.Normal; } } // To copy a file to another location and // overwrite the destination file if it already exists. if (File.Exists(sourceFile)) { File.SetAttributes(sourceFile, FileAttributes.Normal); File.Copy(sourceFile, destFile, true); } // To copy all the files in one directory to another directory. // Get the files in the source folder. (To recursively iterate through // all subfolders under the current directory, see // "How to: Iterate Through a Directory Tree.") // Note: Check for target path was performed previously // in this code example. if (Directory.Exists(destFile) && Directory.Exists(sourcePath)) { //Now Create all of the directories foreach (string dirPath in Directory.GetDirectories(sourceFile, "*", SearchOption.AllDirectories)) Directory.CreateDirectory(dirPath.Replace(sourceFile, destFile)); //Copy all the files & Replaces any files with the same name foreach (string newPath in Directory.GetFiles(sourceFile, "*.*", SearchOption.AllDirectories)) File.Copy(newPath, newPath.Replace(sourceFile, destFile), true); } }
- Marcado como Resposta Filipe B CastroModerator quarta-feira, 19 de dezembro de 2018 18:34
Todas as Respostas
-
Boa tarde, Osvaldo1br. Tudo bem?
Obrigado por usar o fórum MSDN.
Essa seria uma questão de "How to/Customização" ou "Break Fix/Erro"?
Atenciosamente,Filipe B de Castro
Esse conteúdo é fornecido sem garantias de qualquer tipo, seja expressa ou implícita
MSDN Community Support
Por favor, lembre-se de Marcar como Resposta as postagens que resolveram o seu problema. Essa é uma maneira comum de reconhecer aqueles que o ajudaram e fazer com que seja mais fácil para os outros visitantes encontrarem a resolução mais tarde.
-
-
Não se o que aconteceu, sem modificar nada, quando fui testar hoje boa parte dos erros tinham sumido, o que me permitiu corrigir o resto.
o arquivo ficou assim
public void CopiarColar(string fileName, string sourcePath, string targetPath) { File.SetAttributes(sourcePath, FileAttributes.Normal); File.SetAttributes(targetPath, FileAttributes.Normal); //string fileName = "test.txt"; //string sourcePath = @"C:\Users\Public\TestFolder"; //string targetPath = @"C:\Users\Public\TestFolder\SubDir"; // Use Path class to manipulate file and directory paths. string sourceFile = Path.Combine(sourcePath, fileName); string destFile = Path.Combine(targetPath, fileName); // To copy a folder's contents to a new location: // Create a new target folder, if necessary. if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); //.Attributes=FileAttributes.Normal; } if (Directory.Exists(sourceFile)) { if (!Directory.Exists(destFile)) { Directory.CreateDirectory(destFile);//.Attributes = FileAttributes.Normal; } } // To copy a file to another location and // overwrite the destination file if it already exists. if (File.Exists(sourceFile)) { File.SetAttributes(sourceFile, FileAttributes.Normal); File.Copy(sourceFile, destFile, true); } // To copy all the files in one directory to another directory. // Get the files in the source folder. (To recursively iterate through // all subfolders under the current directory, see // "How to: Iterate Through a Directory Tree.") // Note: Check for target path was performed previously // in this code example. if (Directory.Exists(destFile) && Directory.Exists(sourcePath)) { //Now Create all of the directories foreach (string dirPath in Directory.GetDirectories(sourceFile, "*", SearchOption.AllDirectories)) Directory.CreateDirectory(dirPath.Replace(sourceFile, destFile)); //Copy all the files & Replaces any files with the same name foreach (string newPath in Directory.GetFiles(sourceFile, "*.*", SearchOption.AllDirectories)) File.Copy(newPath, newPath.Replace(sourceFile, destFile), true); } }
- Marcado como Resposta Filipe B CastroModerator quarta-feira, 19 de dezembro de 2018 18:34