I need to move all files from source folder to destination folder. How can I easily extract file name from file path name?
string newPath = "C:\\NewPath";
string[] filePaths = Directory.GetFiles(_configSection.ImportFilePath);
foreach (string filePath in filePaths)
{
// extract file name and add new path
File.Delete(filePath);
}
Try the following:
string newPathForFile = Path.Combine(newPath, Path.GetFileName(filePath));
Path.GetFileName(filePath)
use DirectoryInfo and Fileinfo instead of File and Directory, they present more advanced features.
DirectoryInfo di =
new DirectoryInfo("Path");
FileInfo[] files =
di.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo f in files)
f.MoveTo("newPath");
You may want to try the FileInfo.MoveTo method (code example at the following link):
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.moveto.aspx
You can do it like this:
string newPath = "C:\\NewPath";
string[] filePaths = Directory.GetFiles(_configSection.ImportFilePath);
foreach (string filePath in filePaths)
{
string newFilePath = Path.Combine(newPath, Path.GetFileName(filePath);
File.Move(filePath, newFilePath);
}
Related
I have a list of Strings with a series of names, I want to find these names in the source directory and copy them to the destination.
This is what I am trying but with this I copy all source directory in target directory:
List<string> ncs = new List<string>();
ncs = getNames();
foreach (var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
foreach (var directory in Directory.GetDirectories(sourceDir))
CopyNCfromTo(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
I am trying in this way too:
List<string> ncs = new List<string>();
ncs = getNames();
for (int i = 0; i < ncs.Count; i++)
{
FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles(ncs[i].ToString());
}
I thought to loop the list and the look for every file in the source folder, how could I do this?
I assume that the ncs list containing only names not the file path or the file name with extension.
foreach (var file in Directory.GetFiles(sourceDir))
if (ncs.Contains(Path.GetFileName(file).Split('.').First()))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
This is happening because foreach is browsing the files contained in the folder and not the list of names, that way, all files are copied to the destination folder.
foreach(string fileName in ncs){
string path = sourceDir + fileName;
bool result = System.IO.File.Exists(path);
if(result == true){
string destinationPath = targetDir + fileName;
System.IO.File.Copy(path,destinationPath);
}
}
That way you go through the list of names and check if the file exists, if it exists, copy the file to the destination folder
You can iterate over ncs, build the source and destination paths, and do a copy if the file exists.
Caveat: File.Exists() can introduce a race condition. If you are not confident no other process is working in that folder then you should handle IO exceptions.
string sourceDir = "C:\\....";
string targetDir = "C:\\....";
foreach (string filename in ncs)
{
string srcFile = Path.Combine(sourceDir, filename);
string destFile = Path.Combine(targetDir, filename);
if (File.Exists(srcFile))
{
File.Copy(srcFile, destFile);
}
}
So I want to log what happens when I backup files but I'm not sure how to make it work for files in subdirectories aswell.
Right now I have this code that works for all files in the selected directory but doesn't work for subdirectory files
private void LogBackup(string sourceDirName, string destDirName)
{
List<string> lines = new List<string>();
string logDestination = this.tbox_LogFiles.Text;
string dateString = DateTime.Now.ToString("MM-dd-yyyy_H.mm.ss");
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
lines.Add("FILES TO COPY:");
lines.Add("--------------");
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files
.Where(f => !extensionsToSkip.Contains(f.Extension) && !filesToSkip.Contains(f.FullName)).ToList())
{
string desttemppath = Path.Combine(destDirName, file.Name);
string sourcetemppath = Path.Combine(sourceDirName, file.Name);
lines.Add("SOURCE FILE:");
lines.Add(sourcetemppath);
lines.Add("DESTINATION FILE:");
lines.Add(desttemppath);
lines.Add("");
}
foreach (DirectoryInfo subdir in dirs
.Where(f => !foldersToSkip.Contains(f.FullName)))
{
//NOT SURE WHAT TO WRITE HERE
}
using (StreamWriter writer = new StreamWriter(logDestination + #"\LOG " + dateString + ".txt"))
{
foreach (string line in lines)
{
writer.WriteLine(line);
}
}
}
Any ideas please?
Include the SearchOption.AllDirectories and you will get all sub directories:
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories("*", SearchOption.AllDirectories);
when you now loop through the directories, you will have also the first level of subdirectories and for each directory just get the files that it contains
foreach (DirectoryInfo subdir in dirs)
{
FileInfo[] files = subdir.GetFiles();
......
I have following List<String> fileNames getting passed to my method,
I want to remove the sub-path from that and create the left out file structure
string subPath = "C:\\temp\\test"
List<string> filesIncoming = new List[]{#"C:\temp\test\a.txt", #"C:\temp\test\intest\a.txt"};
string outputDir = "C:\\temp3\\temp";
Output should be:
C:\\temp3\temp\a.txt
C:\\temp3\temp\intest\a.txt
This is what I am trying
foreach (var file in files)
{
var directory = Path.GetDirectoryName(file);
DirectoryInfo source = new DirectoryInfo(directory);
var fileName = Path.GetFileName(file);
var destDir = Path.Combine(destinatonFilePath, source.Name); //how do I remove sub-path from source.Name and combine the paths properly?
CreateDirectory(new DirectoryInfo(destDir));
File.Copy(file, Path.Combine(destDir, fileName), true);
}
I think you should use the old good string.Replace to remove the common base path from your incoming files and replace it with the common base path for the output files
string subPath = "C:\\temp\\test"
string outputDir = "C:\\temp3\\temp";
foreach (var file in files)
{
// Not sure how do you have named these two variables.
string newFilePath = file.Replace(subPath, outputDir);
Directory.CreateDirectory(Path.GetDirectoryName(newFilePath));
File.Copy(file, newFilePath, true);
}
I am trying to copy all format file (.txt,.pdf,.doc ...) file from source folder to destination.
I have write code only for text file.
What should I do to copy all format files?
My code:
string fileName = "test.txt";
string sourcePath = #"E:\test222";
string targetPath = #"E:\TestFolder";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
Code to copy file:
System.IO.File.Copy(sourceFile, destFile, true);
Use Directory.GetFiles and loop the paths
string sourcePath = #"E:\test222";
string targetPath = #"E:\TestFolder";
foreach (var sourceFilePath in Directory.GetFiles(sourcePath))
{
string fileName = Path.GetFileName(sourceFilePath);
string destinationFilePath = Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFilePath, destinationFilePath , true);
}
I kinda got the impression you wanted to filter by extension. If so, this will do it. Comment out the parts I indicate below if you don't.
string sourcePath = #"E:\test222";
string targetPath = #"E:\TestFolder";
var extensions = new[] {".txt", ".pdf", ".doc" }; // not sure if you really wanted to filter by extension or not, it kinda seemed like maybe you did. if not, comment this out
var files = (from file in Directory.EnumerateFiles(sourcePath)
where extensions.Contains(Path.GetExtension(file), StringComparer.InvariantCultureIgnoreCase) // comment this out if you don't want to filter extensions
select new
{
Source = file,
Destination = Path.Combine(targetPath, Path.GetFileName(file))
});
foreach(var file in files)
{
File.Copy(file.Source, file.Destination);
}
string[] filePaths = Directory.GetFiles(#"E:\test222\", "*", SearchOption.AllDirectories);
use this, and loop through all the files to copy into destination folder
there are in the files of my listbox ı want copy files these specified path for example c:\ or any path but error be (value cannot be null parameter name path) error how ı can copy specified path ı wirte this code
string source, fileToCopy, target;
string sourcefolder1;
string destinationfolder;
DirectoryInfo di = new DirectoryInfo(destinationfolder);
FileInfo[] annfiles;
foreach (string s in listBox1.Items)
{
fileToCopy = s;
source = Path.Combine(sourcefolder1, fileToCopy);
target = Path.Combine(destinationfolder, fileToCopy);
File.Copy(source, target);
annFiles = di.GetFiles();
}
I think the problem is here:
string destinationfolder;
You declare an empty string and after try to get DirectoryInfo from what? And Empty string? This thrown an Exception. You can see your code like this:
DirectoryInfo di = new DirectoryInfo("");
This code throw always an Exception.
The question is: what you need in "destinationFolder" parameter?
This is a sample file copy:
string sourceFolder = #"C:\Documents";
string destinationFolder = "#"C:\MyDocumentsCopy";
DirectoryInfo directory = new DirectoryInfo(sourceFolder);
FileInfo[] files = directory.GetFiles();
foreach(var file in files)
{
string destinationPath = Path.Combine(destinationFolder, file.Name);
File.Copy(file.Fullname, destinationPath);
}