C# Move files inside dialog's path - c#

I'm struggling with this basic operation.It will be nice if someone can write a working code.So let's say I got folder "AB" on desktop.Folder AB contains subfolder A and subfolder B.Subfolder A contains A.txt and Subfolder B contains B.txt.I want the user to simply choose folder AB via a browser dialog(I did that already) and then,when he clicks on a checkbox,file A.txt will go on subfolder B and B.txt will go on subfolder A.

I will do this for simple folders A and B. You will have to consider the chances of sub-folders as well.
string[] filesA = System.IO.Directory.GetFiles(AsourcePath);
string[] filesB = System.IO.Directory.GetFiles(BsourcePath);
foreach (string s in filesA)
{
System.IO.File.Move(s, AsourcePath);
}
foreach (string s in filesB)
{
System.IO.File.Move(s, BsourcePath);
}
Please Note: You will have consider so many scenarios for this including sub-folders, overwriting, existing files or folders etc.

Assuming that you have the folder path for both A and B folders,
var Afolder = #"D:\AB\A";
var Bfolder = #"D:\AB\B";
SwapFolderFiles(Afolder, Bfolder);
Pass the folder path for both A and B to SwapFolderFiles,
private static void SwapFolderFiles(string AFolder, string BFolder)
{
var AFolderfiles = System.IO.Directory.GetFiles(AFolder);
var BFolderfiles = System.IO.Directory.GetFiles(BFolder);
MoveFiles(AFolder, BFolder, AFolderfiles);
MoveFiles(BFolder, AFolder, BFolderfiles);
}
private static void MoveFiles(string sourceFolder, string destinationFolder, string[] folderfiles)
{
foreach (var file in folderfiles)
{
var filename = file.Substring(file.LastIndexOf("\\")+1);
var source = System.IO.Path.Combine(sourceFolder, filename);
var destination = System.IO.Path.Combine(destinationFolder, filename);
System.IO.File.Move(source, destination);
}
}

Related

How do I move all subfolders in one directory to another folder in c#?

I have a directory with folders and files, and I want to move all the folders into another folder that's inside the directory.
I already can move all the files in the directory(Not including the files in the subfolders), but I am also trying to figure out how to move the subfolders.
string selectedDrive = comboBox1.SelectedItem.ToString();
string folderName = selectedDrive + #"\\Encrypted"; // Creates a directory under the selected drive.
System.IO.Directory.CreateDirectory(folderName);
string moveTo = (selectedDrive + #"\Encrypted");
String [] allFolders = Directory.GetDirectories(selectedDrive); //Should return folder
foreach (String Folder in allFolders)
{
if (!Directory.Exists(moveTo + Folder))
{
FileSystem.CopyDirectory(Folder, moveTo);
}
}
Instead, I have an error at this line FileSystem.CopyDirectory(Folder, moveTo);
saying the following: System.IO.IOException: 'Could not complete operation since source directory and target directory are the same.'
I have reworked your code to make it work in this way:
// source of copies, but notice the endslash, it's required
// if you use the string replace method below
string selectedDrive = #"E:\temp\";
string destFolderName = Path.Combine(selectedDrive, "Encrypted");
System.IO.Directory.CreateDirectory(destFolderName);
// All folders except the one just created
var allFolders = Directory.EnumerateDirectories(selectedDrive)
.Except(new[] { destFolderName });
// Loop over the sources
foreach (string source in allFolders)
{
// this line in framework 4.8,
string relative = source.Replace(selectedDrive, "");
// or this line if using NET Core 6
// string relative = Path.GetRelativePath(selectedDrive, source));
// Create the full destination name
string dest = Path.Combine(destFolderName, relative);
if (!Directory.Exists(dest))
{
FileSystem.CopyDirectory(source, dest);
}
}
Also noted now that you are using a root drive (F:) as source for the directories to copy. In this case you should consider that you have other folders not accessible or not copy-able. (For example the Recycle.bin folder). However you can easily add other exclusions to the array passed to the IEnumerable extension Except
....
.Except(new[] { destFolderName, "Recycle.bin" });

Batch renaming files C#

I have a unity project that i need to rename basically all my files in it to contain a - as a way of easily identifying what assetbundle i need to load it from.
I would need to insert a - at the end of the identifier so for example, testtest.png would become test-test.png and so on.
I currently have this (just want to get the identifier from the file name itself for now) however, the first string in temp is always empty with the second one containing the rest of the file name
foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
string name = file.Split('\\').Last();
if (name.StartsWith(args[0]))
{
string[] temp = name.Split(new[]{args[0]},StringSplitOptions.None);
foreach (string s in temp)
{
Console.WriteLine(s);
}
}
}
D:\renamething\bin\Debug>renamething.exe test
.pdb
I tried Regex for it as well however it produced the same result, empty string in the first one, rest of it in the second.
I don't think that would work, especially the args[0]
Try this:
foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
var fileInfo = new FileInfo(file); //Get FileInfo
if (!fileInfo.Name.StartsWith(args[0], StringComparison.OrdinalIgnoreCase)) //If File doesn't start with the specified arguments, don't process
{
continue;
}
//Consider file -> C:/TestFolder/test.png
var directory = fileInfo.DirectoryName;//Gives C:\TestFolder\
var extension = fileInfo.Extension; //gives ".png"
var fileName = Path.GetFileNameWithoutExtension(fileInfo.Name); //Gives "test"
var modifiedFileName = $"{fileName}-test{extension}"; //Gives "test-test.png
var modifiedFullPath = $"{directory}/{modifiedFileName}";// C:\TestFolder\test-test.png
fileInfo.MoveTo(modifiedFullPath);
}
With the code from #Zee (and #Dai from having a second look over), here is what i ended up in the odd chance that anyone else in the future comes here and needs it
public static void Main(string[] args){
foreach(string file in Directory.GetFiles(Directory.GetCurrentDirectory())){
FileInfo fileInfo=new FileInfo(file);
if(fileInfo.Name.StartsWith(args[0])&&fileInfo.Name.EndsWith(".png"){
string[]temp=Regex.Split(fileInfo.Name, #"(?<!^)(?=[A-Z])");
temp[0]+="-";
File.Move(fileInfo.FullName,String.Concat(temp));
}
}
}

Directory.EnumerateDirectories : Only get back Directores with a special file in it [duplicate]

I wish to get list of all the folders/directories that has a particular file in it. How do I do this using C# code.
Eg: Consider I have 20 folders of which 7 of them have a file named "abc.txt". I wish to know all folders that has the file "abc.txt".
I know that we can do this by looking thru all the folders in the path and for each check if the File.Exists(filename); But I wish to know if there is any other way of doing the same rather than looping through all the folder (which may me little time consuming in the case when there are many folders).
Thanks
-Nayan
I would use the method EnumerateFiles of the Directory class with a search pattern and the SearchOption to include AllDirectories. This will return all files (full filename including directory) that match the pattern.
Using the Path class you get the directory of the file.
string rootDirectory = //your root directory;
var foundFiles = Directory.EnumerateFiles(rootDirectory , "abc.txt", SearchOption.AllDirectories);
foreach (var file in foundFiles){
Console.WriteLine(System.IO.Path.GetDirectoryName(file));
}
EnumerateFiles is only available since .NET Framework 4. If you are working with an older version of the .NET Framework then you could use GetFiles of the Directory class.
Update (see comment from PLB):
The code above will fail if the access to a directory in denied. In this case you will need to search each directory one after one to handle exceptions.
public static void SearchFilesRecursivAndPrintOut(string root, string pattern)
{
//Console.WriteLine(root);
try
{
var childDireactory = Directory.EnumerateDirectories(root);
var files = Directory.EnumerateFiles(root, pattern);
foreach (var file in files)
{
Console.WriteLine(System.IO.Path.GetDirectoryName(file));
}
foreach (var dir in childDireactory)
{
SearchRecursiv(dir, pattern);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
The following shows how to narrow down your search by specific criteria (i.e. include only DLLs that contain "Microsoft", "IBM" or "nHibernate" in its name).
var filez = Directory.EnumerateFiles(#"c:\MLBWRT", "*.dll", SearchOption.AllDirectories)
.Where(
s => s.ToLower().Contains("microsoft")
&& s.ToLower().Contains("ibm")
&& s.ToLower().Contains("nhibernate"));
string[] allFiles = filez.ToArray<string>();
for (int i = 0; i < allFiles.Length; i++) {
FileInfo fInfo = new FileInfo(allFiles[i]);
Console.WriteLine(fInfo.Name);
}

How to get all the files inside a folder?

In my program I have a treeview and a folderbrowser and a datagridview. The user uses the folder browser to choose a folder which contains bunch of shows which all have different seasons. My program displays the folders for the shows and the season folders inside them in the treeview and each time the select a folder from treeview I want it to display all the files inside that folder. I am currectly using this code:
public void fileProcessDirectory(string targetDirectory, string Name)
{
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
FileProcessFile(fileName);
}
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
{
fileProcessDirectory(subdirectory, Name);
break;
}
}
public void FileProcessFile(string path)
{
dataGridView.Rows.Add(path, "New");
}
it shows the files inside the first sub folder that I have. it used to show all the files inside all the folders so I added a break and now it shows the first 3 files and stops there. So I want it to display the files inside the selected subfolder not all the sub folders.
You can try to modify your function as this:
public void FileProcessDirectory(string targetDirectory, string subfolder)
{
// this adds files
foreach (string fileName in Directory.GetFiles(targetDirectory))
{
FileProcessFile(fileName);
}
// if we pass subfolder as empty then nothing happens
if(string.IsNullOrEmpty(subfolder)) return;
// here we find our subfolder and display files for it
FileProcessDirectory(Directory.GetDirectories(targetDirectory).Where(d => d == targetDirectory + "\\" + subfolder).ToArray()[0], null);
}
And the ussage example:
FileProcessDirectory(Directory.GetParent(Directory.GetCurrentDirectory()).FullName, "Debug");
Please correct my understanding if I'm wrong:
user select the folder, then on treeview select the season then they should see in the data grid view all the files inside, correct ?
I implemented in this way
treeView1.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseClick);
if user double click on the treenode it shows all the files inside in the data grid:
void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (treeView1.SelectedNode != null)
{
dataGridView1.Rows.Clear();
string[] fileEntries = System.IO.Directory.GetFiles(treeView1.SelectedNode.Text);
foreach (string fileName in fileEntries)
{
dataGridView1.Rows.Add(Path.GetFileName(fileName));
}
}
}
I guess the problem before maybe caused by the dataGrid not clearing the old files. Hope it helps.

Crawling a directory

I have this test path:
private static string dCrawler = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "TestLetters";
Is there a way to say:
foreach (item in dCrawler)
{
if (item.isFile)
{
// check file info date modified code
} else
{
foreach (fileinfo file in ...
}
}
so far I have only found ways to check a file in a directory. Is the only way to do it by having two separate loops one for files and one for folders?
You can use Directory.GetFiles(); that returns a string[] and use the string value to create your FileInfo. Like this
foreach (string n in Directory.GetFiles(dCrawler))
{
FileInfo b = new FileInfo(n);
}
To get directories, you can similarly use Directory.GetDirectories();
foreach (string n in Directory.GetDirectories(dCrawler))
{
DirectoryInfo b = new DirectoryInfo(n);
}

Categories

Resources