Remove sub-path of File name and create file structure - c#

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);
}

Related

Copy files containing a name from source to destination c#

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);
}
}

Copy and rename directory

I'm trying to modify this code to copy and rename (instead of just move) multiple directories. I have a CSV file that has 2 columns. The "original folder name" and the "new folder name".
using System.Linq;
using System.IO;
string csv = "csv path";
string sourcedir = #"C:\temp1\";
string targetdir = #"C:\temp2\";
string[] items = File.ReadAllLines(csv);
foreach(var item in items)
{
string oldname = item.Split(';')[0];
string newname = item.Split(';')[1];
Directory.Move(sourcedir +oldname, targetdir +newname);
}
When source-folder doesn't contain nested folders then use this way:
string csv = "csv path";
string sourcedir = #"C:\temp1\";
string targetdir = #"C:\temp2\";
var items = File.ReadAllLines(csv);
foreach(var item in items)
{
var paths = item.Split(";");
var sourcePath = Path.Combine(sourcedir, paths[0]);
var targetPath = Path.Combine(targetdir, paths[1]);
System.IO.Directory.CreateDirectory(targetPath);
var files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
var fileName = System.IO.Path.GetFileName(s);
var destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
Otherwise, you need to use recursive traverse through nested folders - see example MS docs 'How to: Copy directories'.

Create files from multiple files contents

I am trying to create new files with the names created by data from lines in several files.
I want to read all lines of just the .txt files in a folder and then create files from that list.
The files are have various amounts of lines and there could be a various amount of .txt files.
Here is the code that I have tried;
static void WriteToFile(string directory, string name)
{
string filename = String.Format(name);
string path = Path.Combine(directory, filename);
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Inserted Text");
}
}
......
string[] allFiles = Directory.GetFiles(folder, "*.txt");
foreach (string file in allFiles)
{
string[] lines = File.ReadAllLines(file);
foreach (string newfile in lines)
{
WriteToFile(folder, newfile);
}
}
This is now creating the files but I need to specify the extension as they are just created as 'file1' instead of 'file1.ext'
File.Create Method (String) returns FileStream. The FileStream must be disposed to flush file. Try using this code to create an empty file:
File.Create(fileName).Dispose();
Also, take a look at the similar question: Creating an empty file in C#.
Without any details of error/exception, to me it seems either permission issue, or character issue.
You can use Path.GetInvalidPathChars with Enumerable.Intersect to check if file path contains invalid characters before creating new file
char[] invalidPathChars = Path.GetInvalidPathChars();
foreach (string newfile in lines)
{
if (invalidPathChars.Intersect(newfile).Any())
{
Console.WriteLine(newfile + " contains invalid characters for file name");
continue;
}
File.Create(newfile);
}
File.Create returns a filestream that you can use to write to the new file. But you are not providing the path that is the argument in Create but the line. The line might be an invalid path.
You can use this query instead:
string invalidCharacters = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
var allPaths = Directory.EnumerateFiles(folder, "*.txt")
.SelectMany(path => File.ReadLines(path))
.Select(line => {
string fileName = line;
foreach (Char c in invalidCharacters)
fileName = fileName.Replace(c.ToString(), "_");
return new{ line, path = Path.Combine(targetFolder, fileName) };
} );
foreach(var p in allPaths)
{
File.WriteAllText(p.path, p.line);
}
Edit: however, that will very likely result in this error:
The specified path, file name, or both are too long. The fully
qualified file name must be less than 260 characters, and the
directory name must be less than 248 characters.
So you need to use a method that shortens the path (f.e. using a logic that appends a number to avoid duplicate names).
static void WriteToFile(string directory, string name)
{
string filename = String.Format(name + ".ini");
string path = Path.Combine(directory, filename);
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Inserted Text");
}
}
......
var allFiles = Directory.GetFiles(folder, "*.txt");
foreach (string file in allFiles)
{
var lines = File.ReadAllLines(file);
foreach (string newfile in lines)
{
WriteToFile(folder, newfile);
}
}

copy all type format file from folder in c#

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

copy multiple files from listbox to specified 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);
}

Categories

Resources