I want to create a simple program that can access all the files in the folder, all of which being the same type of file, and then use a for each to rename all of them.
The new name will be IMG### with the ### being incremental. I know how to do this. How do I reference all the images to be used in a for each?
Example:
For Each X in Folder {
rename stuff here for x
}
All I need to know is how to reference file in the spot of x.
You can go about it along this line of thought:
var files = Directory.GetFiles(path, "*.", SearchOption.AllDirectories);
foreach (string item in files)
{
//You can rename by moving the files into their 'new names'.
//The names are full paths
File.Move(oldName, newName);
}
Related
Im trying to copy files from "source" folder to my "destination" folder, without duplicates. I cant use destination folder to compare as it will eventually get deleted from there. I had gotten help here to make a batch file
Robocopy "source" "destination" "*chr.txt*" "*hdr.txt*" /M
that uses attribute to keep track of files copy before. However I need to do this in C# instead. I know theres command to copy
System.IO.File.Copy(sourceFile, destFile, true);
but not sure how to go about being specific on file name "*chr.txt" and taking care of duplicates.
I need to do this in C# instead
Process.Start("robocopy", "source destination chr.txt hdr.txt /M");
Here is a method I created a while ago that has worked well for me (aside from the checking for duplicates part that I just added and haven't tested). Let me know if any parts of it do not work for what you need.
private static void CopyDirectory(string from, string to)
{
var toFileNames = new DirectoryInfo(to)
.GetFiles()
.Select(f => f.Name)
.ToList();
var directory = new DirectoryInfo(from);
var files = directory.GetFiles();
foreach (var file in files)
if (!toFileNames.Contains(file.Name))
file.CopyTo(Path.Combine(to, file.Name));
var subDirectories = directory.GetDirectories();
foreach (var subDirectory in subDirectories)
{
var newDirectory = Directory.CreateDirectory(Path.Combine(to, subDirectory.Name));
CopyDirectory(subDirectory.FullName, newDirectory.FullName);
}
}
I am developing a desktop application in C#.
I have programmatically created a folder(say ABC) inside the Main folder in C drive in Windows.
I want to know whether an user has created any new folder(by simply right clicking and creating new folder) inside ABC.
If the user has created a new folder then I need to get the details of that folder like folder name and privacy too.
Thanks in advance!
You can get the subdirectories of a folder (in your example, the folder "ABC") as an array of strings by calling the method GetDirectories:
string[] subdirs = Directory.GetDirectories(#"C:\ABC");
Then, if you'd like, you can iterate through all of them:
foreach (string dir in subdirs)
//dir is a path to a subdirectory
Don't forget the using statement!
using System.IO;
You can use DirectoryInfo to get the list of subfolder
DirectoryInfo dirInfo = new DirectoryInfo(#"c:\ABC");
DirectoryInfo[] subFolders = dirInfo.GetDirectories();
I'm not sure what you mean by privacy...
I know that if you want to delete a directory you have to delete all of it's files first.
However if you want to delete a directory which contains empty sub-directories, do you have to delete those sub-directories first? or can you just go ahead and delete the main directory?
Directory.Delete set the recurse flag to true, should do the job, no need to empty them first.
Directory.Delete(path, true);
I have just noticed that your tag refers to IsolatedStorage, in which case you will need to enumerate all the files and folders and delete as you go.
How to: Delete Files and Directories in Isolated Storage
You can try to delete recursively:
var path = Path.GetFullPath(#"C:\Temp\DeleteMe");
Directory.Delete(path,true); // true for recursive
This should delete everything including files if you have the proper permissions.
Why check if it is empty or not when you are going to delete it anyway.
You can use the Directory.Delete(yourpath,true) method only if you are sure that there isn't any readonly file in the directory. else it will throw an exception. Instead you can use your own recursive method like this which will first mark the file as normal before deleting it.
public static void DeleteDirectory(string target_dir)
{
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}
I want to make an exact copy of some files, directories and subdirectories that are on my USB drive I:/ and want them to be in C:/backup (for example)
My USB drive has the following structure:
(just to know, this is an example, my drive has more files, directories and subdirectories)
courses/data_structures/db.sql
games/pc/pc-game.exe
exams/exam01.doc
Well, I am not sure how to start with this but my first idea is to get all the files doing this:
string[] files = Directory.GetFiles("I:");
The next step could be to make a loop and use File.Copy specifying the destination path:
string destinationPath = #"C:/backup";
foreach (string file in files)
{
File.Copy(file, destinationPath + "\\" + Path.GetFileName(file), true);
}
At this point everything works good but not as I wanted cause this doesn't replicate the folder structure. Also some errors happen like the following...
The first one happens because my PC configuration shows hidden files for every folder and my USB has an AUTORUN.INF hidden file that is not hidden anymore and the loop tries to copy it and in the process generates this exception:
Access to the path 'AUTORUN.INF' is denied.
The second one happens when some paths are too long and this generates the following exception:
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, I am not sure how to achieve this and validate each posible case of error. I would like to know if there is another way to do this and how (maybe some library) or something more simple like an implemented method with the following structure:
File.CopyDrive(driveLetter, destinationFolder)
(VB.NET answers will be accepted too).
Thanks in advance.
public static void Copy(string src, string dest)
{
// copy all files
foreach (string file in Directory.GetFiles(src))
{
try
{
File.Copy(file, Path.Combine(dest, Path.GetFileName(file)));
}
catch (PathTooLongException)
{
}
// catch any other exception that you want.
// List of possible exceptions here: http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx
}
// go recursive on directories
foreach (string dir in Directory.GetDirectories(src))
{
// First create directory...
// Instead of new DirectoryInfo(dir).Name, you can use any other way to get the dir name,
// but not Path.GetDirectoryName, since it returns full dir name.
string destSubDir = Path.Combine(dest, new DirectoryInfo(dir).Name);
Directory.CreateDirectory(destSubDir);
// and then go recursive
Copy(dir, destSubDir);
}
}
And then you can call it:
Copy(#"I:\", #"C:\Backup");
Didn't have time to test it, but i hope you get the idea...
edit: in the code above, there are no checks like Directory.Exists and such, you might add those if the directory structure of some kind exists at destination path. And if you're trying to create some kind of simple sync app, then it gets a bit harder, as you need to delete or take other action on files/folders that don't exist anymore.
This generally starts with a recursive descent parser. Here is a good example: http://msdn.microsoft.com/en-us/library/bb762914.aspx
You might want to look into the overloaded CopyDirectory Class
CopyDirectory(String, String, UIOption, UICancelOption)
It will recurse through all of the subdirectories.
If you want a standalone application, I have written an application that copies from one selected directory to another, overwriting newer files and adding subdirectories as needed.
Just email me.
I am currently writing a program which searches My Documents. Currently my program is able to search and copy the main my documents folder but I am unable to make it search sub directory's within the main my documents directory. I have tried multiple methods but none seem to be working out.
Currently I am using the below code to dump the files location into an array called files. sourcePath is declared in an array before hand.
string[] files = System.IO.Directory.GetFiles(sourcePath[loopcounter]);
I then have a loop which copy's the files over to another directory
foreach (string s in files)
Any help as to how to fill the array files with details of files in the sub directories of a folder would be very handy. Thanks in advance!
Use research by pattern and specify you want use recursion :
var allFiles = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"*",
SearchOption.AllDirectories);
foreach (var item in allFiles)
{
// Do Stuff...
}
If you want details about each file, then GetFiles returns you array of names. Pass each name to FileInfo API.