Moving files based on name to the corresponding folder - c#

Hello everyone and well met! I have tried a lot of different methods/programs to try and solve my problem. I'm a novice programmer and have taken a Visual Basic Class and Visual C# class.
I'm working with this in C#
I started off by making a very basic move file program and it worked fine for one file but as I mentioned I will be needing to move a ton of files based on name
What I am trying to do is move .pst (for example dave.pst) files from my exchange server based on username onto a backup server in the users folder (folder = dave) that has the same name as the .pst file
The ideal program would be:
Get files from the folder with the .pst extension
Move files to appropriate folder that has the same name in front of the .pst file extension
Update:
// String pstFileFolder = #"C:\test\";
// var searchPattern = "*.pst";
// var extension = ".pst";
//var serverFolder = #"C:\test3\";
// String filename = System.IO.Path.GetFileNameWithoutExtension(pstFileFolder);
// Searches the directory for *.pst
DirectoryInfo sourceDirectory = new DirectoryInfo(#"C:\test\");
String strTargetDirectory = (#"C:\test3\");
Console.WriteLine(sourceDirectory);
Console.ReadKey(true);>foreach (FileInfo file in sourceDirectory.GetFiles()) {
Console.WriteLine(file);
Console.ReadKey(true);
// Try to create the directory.
System.IO.Directory.CreateDirectory(strTargetDirectory);
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}
This is just a simple copy procedure. I'm completely aware. The
Console.WriteLine(file);
Console.ReadKey(true);
Are for verification purpose right now to make sure I'm getting the proper files and I am. Now I just need to find the folder based on the name of the .pst file(the folder for the users are already created), make a folder(say 0304 for the year), then copy that .pst based on the name.
Thanks a ton for your help guys. #yuck, thanks for the code.

Have a look at the File and Directory classes in the System.IO namespace. You could use the Directory.GetFiles() method to get the names of the files you need to transfer.

Here's a console application to get you started. Note that there isn't any error checking and it makes some assumptions about how the files are named (e.g. that they end with .pst and don't contain that elsewhere in the name):
private static void Main() {
var pstFileFolder = #"C:\TEMP\PST_Files\";
var searchPattern = "*.pst";
var extension = ".pst";
var serverFolder = #"\\SERVER\PST_Backup\";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, searchPattern)) {
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Gets the user name based on file name
// e.g. DaveSmith.pst would become DaveSmith
var userName = theFileInfo.Name.Replace(extension, "");
// Sets up the destination location
// e.g. \\SERVER\PST_Backup\DaveSmith\DaveSmith.pst
var destination = serverFolder + userName + #"\" + theFileInfo.Name;
File.Move(file, destination);
}
}

System.IO is your friend in this case ;)
First, Determine file name by:
String filename = System.IO.Path.GetFileNameWithoutExtension(SOME_PATH)
To make path to new folder, use Path.Combine:
String targetDir = Path.Combine(SOME_ROOT_DIR,filename);
Next, create folder with name based on given fileName
System.IO.Directory.CreateDirectory(targetDir);
Ah! You need to have name of file, but with extension this time. Path.GetFileName:
String fileNameWithExtension = System.IO.Path.GetFileName(SOME_PATH);
And you can move file (by File.Move) to it:
System.IO.File.Move(SOME_PATH,Path.Combine(targetDir,fileNameWithExtension)
Laster already show you how to get file list in folder.

I personally prefer DirectoryInfo because it is more object-oriented.
DirectoryInfo sourceDirectory = new DirectoryInfo("C:\MySourceDirectoryPath");
String strTargetDirectory = "C:\MyTargetDirectoryPath";
foreach (FileInfo file in sourceDirectory.GetFiles())
{
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}

Related

Check if filename exist in the folder directory

Hi I have a code that you can save file and give specific file naming.
the problem is how can I check if file exist in the folder directory.
What I'm trying to do is like this.
FileInfo fileInfo = new FileInfo(oldPath);
if (fileInfo.Exists)
{
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
fileInfo.MoveTo(string.Format("{0}{1}{2}", newPath, extBox1t.Text + "_" + textBox2.Text + "_" + textBox3.Text, fileInfo.Extension));
im trying to add MessageBox.Show in the below
if (!Directory.Exists(newPath))
{
MessageBox.Show("File Exist. Please Rename!");
Directory.CreateDirectory(newPath);
But it does not work. Or is there a way to add extension name at the last part of filename it should like this
Example: STACKOVERFLOWDOTCOME_IDNUM_11162022_0
if STACKOVERFLOWDOTCOME_IDNUM_11162022 exist it will rename to STACKOVERFLOWDOTCOME_IDNUM_11162022_0
it will add _0 at the last part.
One way to do it is to write a method that extracts the directory path, name, and extension of the file from a string that represents the full file path. Then we can create another variable to act as the "counter", which we'll use to add the number at the end of the file name (before the extension). We can then create a loop that checks if the file exists, and if it doesn't we'll increment the counter, insert it into the name, and try again.
For example:
public static string GetUniqueFileName(string fileFullName)
{
var path = Path.GetDirectoryName(fileFullName);
var name = Path.GetFileNameWithoutExtension(fileFullName);
var ext = Path.GetExtension(fileFullName);
var counter = 0;
// Keep appending a new number to the end of the file name until it's unique
while(File.Exists(fileFullName))
{
// Since the file name exists, insert an underscore and number
// just before the file extension for the next iteration
fileFullName = Path.Combine(path, $"{name}_{counter++}{ext}");
}
return fileFullName;
}
To test it out, I created a file at c:\temp\temp.txt. After running the program with this file path, it came up with a new file name: c:\temp\temp_0.txt

How can I access a local folder inside a WPF project to load and store files?

I need a library of vector files, where the same files have to be used every time. I want to load them from a folder and have the option to store new ones.
I tried having a library folder inside the WPF project that contains the files:
Solution/Project/Library/file1.dxf
I load them like this:
string currentDir = Directory.GetCurrentDirectory();
var cutOff = currentDir.LastIndexOf(#"\bin\");
var folder = currentDir.Substring(0, cutOff) + #"\Library\";
string[] filePaths = Directory.GetFiles(folder, "*.dxf");
This worked when running on the PC the project was buid, but the program crashes when the .exe is run on another PC. How do I fix this or is there a better approach to this?
Create a subfolder under Environment.SpecialFolder.ApplicationData, read the files in the library folder if it exists. If not create it and save the existing library files to it (here from resources):
string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appFolder + #"\MyAppLibrary\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// Add existing files to that folder
var rm = Properties.Resources.ResourceManager;
var resSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (var res in resSet)
{
var entry = ((DictionaryEntry)res);
var name = (string)entry.Key;
var file = (byte[])rm.GetObject(name);
var filePath = path + name + ".dxf";
File.WriteAllBytes(filePath, file);
}
}
// Load all files from the library folder
string[] filePaths = Directory.GetFiles(path, "*.dxf");
Thanks Jonathan Alfaro and Clemens!

Application: Application Launcher, can't Move directory, it's being used by another process

I'm writing application launcher as a Window Application in C#, VS 2017. Currently, having problem with this piece of code:
if (System.IO.Directory.Exists(extractPath))
{
string[] files = System.IO.Directory.GetFiles(extractPath);
string[] dirs = Directory.GetDirectories(extractPath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
var fileName = System.IO.Path.GetFileName(s);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.File.Move(s, destFile);
}
foreach (string dir in dirs)
{
//var dirSplit = dir.Split('\\');
//var last = dirSplit.Last();
//if (last != "Resources")
//{
var fileName = System.IO.Path.GetFileName(dir);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.Directory.Move(dir, destFile);
//}
}
}
I'm getting well known error
"The process cannot access the file 'XXX' because it is being used by another process."
I was looking for solution to fix it, found several on MSDN and StackOvervflow, but my problem is quite specific. I cannot move only 1 directory to another, which is Resources folder of my main application:
Here is my explanation why problem is specific:
I'm not having any issues with moving other files from parent directory. Error occurs only when loop reaches /Resources directory.
At first, I was thinking that it's beeing used by VS instantion, in which I've had main app opened. Nothing have changed after closing VS and killing process.
I've copied and moved whole project to another directory. Never opened it in VS nor started via *.exe file, to make sure that none of files in new, copied directory, is used by any process.
Finally, I've restarted PC.
I know that this error is pretty common when you try to Del/Move files, but in my case, I'm sure that it's being used only by my launcher app. Here is a little longer sample code to show what files operation I'm actually doing:
private void RozpakujRepo()
{
string oldPath = #"path\Debug Kopia\Old";
string extractPath = #"path\Debug Kopia";
var tempPath = #"path\ZipRepo\RexTempRepo.zip";
if (System.IO.File.Exists(tempPath) == true)
{
System.IO.File.Delete(tempPath);
}
System.IO.Compression.ZipFile.CreateFromDirectory(extractPath, tempPath);
if (System.IO.Directory.Exists(oldPath))
{
DeleteDirectory(oldPath);
}
if (!System.IO.Directory.Exists(oldPath))
{
System.IO.Directory.CreateDirectory(oldPath);
}
if (System.IO.Directory.Exists(extractPath))
{
string[] files = System.IO.Directory.GetFiles(extractPath);
string[] dirs = Directory.GetDirectories(extractPath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
var fileName = System.IO.Path.GetFileName(s);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.File.Move(s, destFile);
}
foreach (string dir in dirs)
{
//var dirSplit = dir.Split('\\');
//var last = dirSplit.Last();
//if (last != "Resources")
//{
var fileName = System.IO.Path.GetFileName(dir);
var destFile = System.IO.Path.Combine(oldPath, fileName);
System.IO.Directory.Move(dir, destFile);
//}
}
}
string zipPath = #"path\ZipRepo\RexRepo.zip";
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
And now, my questions:
Can it be related to file types (.png, .ico, .bmp) ?
Can it be related to fact, that those resources files are being used like, as, for example .exe file icon in my main application? Or just because those are resources files?
Is there anything else what I'm missing and what can cause the error?
EDIT:
To clarify:
There are 2 apps:
Main Application
Launcher Application (to launch Main Application)
And Resources folder is Main Application/Resources, I'm moving it while I'm doing application version update.
It appeared that problem is in different place than in /Resources directory. Actually problem was with /Old directory, because it caused inifinite recurrence.

Cannot move a file to another folder. Error returns on a wrong path

Here's my code in moving excel file to be specific..
if (Directory.GetFiles(destinationPath, "*.xls").Length != 0)
{
//Move files to history folder
string[] files = Directory.GetFiles(destinationPath); //value -- D://FS//
foreach (string s in files)
{
var fName = Path.GetFileName(s); //12232015.xls
var sourcePath = Path.Combine(destinationPath, fName);
var destFile = Path.Combine(historyPath, fName); // -- D://FS//History
File.Move(fName, destFile);
}
}
But it gets an error of
Could not find file 'D:\Project\ProjectService\bin\Debug\12232015.xls'.
Why it finds under my project not on the specific folder i set?
Thank you.
You're only using the name of the file:
var fName = Path.GetFileName(s); //12232015.xls
//...
File.Move(fName, destFile);
Without a complete path, the system will look in the current working directory. Which is the directory where the application is executing.
You should use the entire path for the source file:
File.Move(sourcePath, destFile);
Explicitly specifying the full path is almost always the best approach. Relative paths are notoriously difficult to manage.
There is an Logical error. Change
File.Move(fName, destFile);
to
File.Move(sourcePath, destFile);
as fName only contains file name and not fullpath. The file is checked in working directory.

Automatically create directories from long paths

I have a collection of files with fully qualified paths (root/test/thing1/thing2/file.txt). I want to foreach over this collection and drop the file into the location defined in the path, however, if certain directories don't exist, I want them to great created automatically. My program has a default "drop location", such as z:/. The "drop location" starts off empty, so in my example above, the first item should automatically create the directories needed to create z:/root/test/thing1/thing2/file.txt. How can I do this?
foreach (var relativePath in files.Keys)
{
var fullPath = Path.Combine(defaultLocation, relativePath);
var directory = Path.GetDirectoryName(fullPath);
Directory.CreateDirectory(directory);
saveFile(fullPath, files[relativePath]);
}
where files is IDictionary<string, object>.
string somepath = #"z:/root/test/thing1/thing2/file.txt";
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName( ( somepath ) );
Directory.CreateDirectory("/root/...")
Creates all directories and subdirectories in the specified path
Check IO namespace (Directory, Path), I think they'll help you
using System.IO
Then check it..
string fileName =#"d:/root/test/thing1/thing2/file.txt";
string directory = Path.GetDirectoryName(fileName);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
string filename = "c:\\temp\\wibble\\wobble\\file.txt";
string dir = Path.GetDirectoryName(filename);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.Create(filename);
with suitable exception handling, of course.
I've found setting the "default location" at the start of execution to be helpful and reduce a bit of redundant code (e.g., Path.Combine(defaultLocation, relativePath)).
Example:
var defaultLocation = "z:/";
Directory.SetCurrentDirectory(defaultLocation);
Directory.SetCurrentDirectory(AppContext.BaseDirectory);

Categories