Copy everything in a Directory and rename copied Files - c#

I try to copy everything in a Folder to another, in this case from "sourceFolder" to "targetFolder".
Lets say "sourceFolder" would have two Files in it and 2 subfolder with one additional File:
(i try to show it)
//sourceFolder
//├File1.txt
//├File2.txt
//├Subfolder1
//| └File3.txt
//|
//└Subfolder2
// └File4.txt
Now I'm trying to copy all of those files and subfolders from "sourceFolder" to "targetFolder", the subfolders shall be titled the same and on the Files i would to add "a" in front of "Filex.txt"(Exaple: "aFilex.txt")
Thats what im tring to get:
//targetFolder
//├aFile1.txt
//├aFile2.txt
//├Subfolder1
//| └aFile3.txt
//|
//└Subfolder2
// └aFile4.txt
current Code:
string[] sourceDirectoryFiles = Directory.GetFiles(sourceFolderTextbox.Text);
string[] sourceDirectorysubfolders = Directory.GetDirectories(targetFolderTextbox.Text);
string sourcedirectory = sourceFolderTextbox.Text;
string targetdirectory = targetFolderTextbox.Text;
if (Directory.Exists(sourceDirectorysubfolders[0]))
{
foreach (string sourceFilePath in sourceDirectorysubfolders)
{
if (!Directory.Exists(sourceFilePath))
{
Directory.CreateDirectory(sourceFilePath.Replace(sourcedirectory, targetdirectory));
}
}
}
foreach (string sourceFilePath in sourceDirectoryFiles )
{
string newsourcefilePath = String.Empty;
string newfilePath = String.Empty;
string FileName = System.IO.Path.GetFileName(sourceFilePath);
newsourcefilePath = sourcedirectory + "\\a" + FileName;
System.IO.File.Copy(sourceFilePath, newfilePath ,true)
}
I hope, I asked clear :)
otherwise I'll answer your questions :)
I'm not good at English or programming so constructive criticism is welcome :)

Have modified the solution in this SO Question to suit your needs. Hope it helps.
void Copy(string sourcePath, string targetPath)
{
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
string newPath;
foreach (string srcPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
{
newPath = srcPath.Replace(sourcePath, targetPath);
newPath = newPath.Insert(newPath.LastIndexOf("\\") + 1, "a"); //prefixing 'a'
newPath = newPath + ".example";
File.Copy(srcPath, newPath, true);
}
}

Related

Copy files from folder A to folder B

I want to copy some of the content of a folder (recursively). only files that contain a specific pattern.
Here there's a method that copies the entire content. no matter what files inside.
https://stackoverflow.com/a/3822913/7028967
Do you have any ideas on how can I copy a specific file inside some subfolder with a given pattern?
for example:
-- rootFolder
---- filename.txt
CopyContent(src, dest, *.txt)
Below sample code to copy all the files from the source directory to destination folder in exact same folder structure :
public static void Copy()
{
string sourceDir = #"C:\test\source\";
string destination = #"C:\test\destination\";
string[] textFiles = Directory.GetFiles(sourceDir, "*.txt", SearchOption.AllDirectories);
foreach (string textFile in textFiles)
{
string fileName = textFile.Substring(sourceDir.Length);
string directoryPath = Path.Combine(destination, Path.GetDirectoryName(fileName));
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
File.Copy(textFile, Path.Combine(directoryPath, Path.GetFileName(textFile)), true);
}
}
Updated:
I used this solution. and it works for me!
private static void CopyContentFolder(string sourcePath, string targetPath, bool isFileOverridable, string pattern = "*.*")
{
string[] sourceFiles = Directory.GetFiles(sourcePath, pattern, SearchOption.AllDirectories);
foreach (string sourceFilePath in sourceFiles)
{
string destinationFilePath = string.Empty;
destinationFilePath = sourceFilePath.Replace(sourcePath, targetPath);
EvaluatePath(destinationFilePath);
File.Copy(sourceFilePath, destinationFilePath, isFileOverridable);
}
}
private static void EvaluatePath(string path)
{
try
{
string folder = Path.GetDirectoryName(path);
if (!Directory.Exists(folder))
{
DirectoryInfo di = Directory.CreateDirectory(folder);
}
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}

Delete specific line from a text file which i don't have the name

i need to find and delete all lines wich contain the word "recto",
i did search in stackoverflow forum, but all what i found is do that (delete the line) using path (Directory & FileName).
in my case i want to delete the line contain "recto" in all fils with specific extention (*.txt) in the directory.
thanks for help
here is my code so far
string sourceDir = #"C:\SRCE\";
string destinDir = #"C:\DIST\";
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
using (StreamReader sr_ = new StreamReader
(sourceDir + Path.GetFileName(file)))
{
string line = sr_.ReadLine();
if (line.Contains("recto"))
{
File.Copy(file, destinDir + Path.GetFileName(file));
string holdName = sourceDir + Path.GetFileName(file);
}
sr_.DiscardBufferedData();
sr_.Close();
}
}
}
You can try something like this. You were only identifying the files with the word but not making any try to remove it. At the end, you were copying the files that included the word "recto"
string sourceDir = #"C:\SRCE\";
string destinDir = #"C:\DIST\";
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
using (StreamReader sr_ = new StreamReader
(sourceDir + Path.GetFileName(file)))
{
string res = string.Empty;
while(!sr_.EndOfStream)
{
var l = sr_.ReadLine();
if (l.Contains("recto"))
{
continue;
}
res += l + Environment.NewLine;
}
var streamWriter = File.CreateText(destinDir + Path.GetFileName(file));
streamWriter.Write(res);
streamWriter.Flush();
streamWriter.Close();
}
}
If the files are not really big you can simplify a lot your code reading all lines in memory, processing the lines with Linq and then rewriting the files
string sourceDir = #"C:\SRCE\";
string destinDir = #"C:\DIST\";
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
var lines = File.ReadLines(file);
var result = lines.Where(x => x != "recto").ToArray();
File.WriteAllLines(Path.Combine(destinDir, Path.GetFileName(file)), result);
}

Get files from a folder that I have created in Xamarin.Android

I want get all files from an external storage folder(wall_e_imgs)..Here are codes-
public void getImages()
{
var path1 = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.ToString();
string path = System.IO.Path.Combine(path1, "wall_e_imgs");
//var files= System.IO.Directory.GetFiles(Android.OS.Environment.ExternalStorageDirectory.ToString() + "wall_e_imgs");
//var files = System.IO.Directory.GetFiles(path);
//string path = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/wall_e_imgs";
//File directory=new File(path);
Java.IO.File directory = new Java.IO.File(path);
Java.IO.File[] files = directory.ListFiles();//always count is 0 even though there are lot files there
foreach (var i in files)
{
FileInfo info = new FileInfo(i.Name);
if (info.Name.Contains("Wall_e"))
{
di.Add(new DownloadedImages { Path1 = info.DirectoryName, Name1 = info.FullName });
}
}
}
But it always give 0 files even though there are lot of files.
Try this
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "yourfoldername";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var filesList = Directory.GetFiles(folder);
foreach (var file in filesList)
{
var filename = Path.GetFileName(file);
}
Try something like this:
// Use whatever folder path you want here, the special folder is just an example
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "wall_e_imgs");
if (Directory.Exists(folderPath))
{
var files = Directory.EnumerateFiles(folderPath);
foreach (var file in files)
{
// Do your stuff
}
}
Please note that this uses the Directory class from System.IO, not Java.IO
ffilelist will contain a list of mp3 files in "/storage/emulated/0/Music/"
string phyle;
string ffilelist = "";
public void listfiles()
{
try
{
var path1 = "/storage/emulated/0/Music/";
var mp3Files = Directory.EnumerateFiles(path1, "*.mp3", SearchOption.AllDirectories);
foreach (string currentFile in mp3Files)
{
phyle = currentFile;
ffilelist = ffilelist + "\n" + phyle;
}
//playpath(phyle); // play the last file found
}
catch (Exception e9)
{
Toast.MakeText(ApplicationContext, "ut oh\n"+e9.Message , ToastLength.Long).Show();
}
}

How can i get files specific files names from directory?

string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry, "*.jpg");
But not only gif i want to specify that also it will be only files that contains the name infrared. For example i have files name 0infrared.gif and also 0visible.gif and i want to get all the files that are infrared.
This will get you all files with infrared in file name and with extension jpg
string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry,
"*infrared*.jpg");
string[] list = Directory.GetFiles(
countriesMainPath + "\\" + currentDownloadCountry,
"*infrared*.*");
This will return all the files contain infrared in their file name.
I think this may be what you look for. ref: MSDN
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
{
string[] searchPatterns = searchPattern.Split('|');
List<string> files = new List<string>();
foreach (string sp in searchPatterns)
files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption));
files.Sort();
return files.ToArray();
}
Usage
var wantedImgs = GetFiles(
dirYouWant, "*infrared*.jpg|*infrared*.gif",
earchOption.TopDirectoryOnly);
string partialName = "infrared";
DirectoryInfo dir = new DirectoryInfo(#"c:\");
FileInfo[] filesInDir = dir.GetFiles("*" + partialName + "*.*");
foreach (FileInfo foundFile in filesInDir)
{
string fullName = foundFile.FullName;
Console.WriteLine(fullName);
}
maybe *infrared*.(jpg|gif) will work

Copy file from source directory to destination C#

I would like to copy my files from source folder to my dest. folder
The location / URL(Name of the column in the table) I got it from here GetDataByGeneralRoot();
Now I would like to copy those file from that URL to a new directory.
What I have done is:
DataSet1.T_DocumentsDataTable docTab = doc.GetDataByGeneralRoot();
string gerneralRootPath = docTab.Rows[0]["URL"].ToString();
gerneralRootPath = gerneralRootPath.Remove(gerneralRootPath.IndexOf("PDF") + 4);
string datadirectory = "//ch-s-0001535/G/inetpub/DocAddWeb/DataSource/";
string final = datadirectory + gerneralRootPath;
foreach (string path in Directory.GetFiles(final, "*.*", SearchOption.AllDirectories))
{
string t = path.Substring(path.IndexOf("\\") + 1);
File.Copy(t, t.Replace(final + t, rootFolderAbsolutePath));
}
My issue / problem is how can I say that I want to get only the files from URL that I got from my method GetDataByGeneralRoot and not all the files what is now happening.
HERE is how my tabel looks like:
I think you want something like this
public void copyAll(DataSet ds, Doc doc, string rootPath, string rootTargetPath)
{
ds.T_DocumentsDataTable docTab = doc.GetDataByGeneralRoot();
string datadirectory = "//ch-s-0001535/G/inetpub/DocAddWeb/DataSource/";
string final = datadirectory + rootPath;
foreach (var row in docTab.Rows)
{
var sourceFile = "//ch-s-0001535/G/inetpub/DocAddWeb/DataSource/" + row["URL"].ToString();
string targetPath = rootTargetPath + row["URL"].ToString();
File.Copy(sourceFile, rootTargetPath);
}
}

Categories