Dynamic File Paths - c#

Suppose I had a particular directory on C# in the following format:
#"C:\blabla\bla\0.0.1.63\blabla.png";
The "0.0.1.63" changes occasionally due to updates to the software and so on.
I want to know how I can assign a "..\" - similar effect for that particular directory to be dynamic. Because I do not know the update sequence.
So, how do I make it so that the directory stays the same, while that particular part of the directory (0.0.1.63) is an "unknown" directory.

You can use the DirectoryInfo.EnumerateDirectories and the DirectoryInfo.EnumerateFileSystemInfos methods to find your file, you could then strip the filename from the FileInfo objects FullName and use the result. Something like this should work.
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = getPath();
openFileDialog1.ShowDialog();
}
private string getPath()
{
DirectoryInfo di = new DirectoryInfo(#"C:\blabla\bla\");
foreach (var d in di.EnumerateDirectories())
{
foreach(var fi in d.EnumerateFileSystemInfos())
{
if (fi.Name == "blabla.png")
{
return fi.FullName.Replace(fi.Name,"");
}
}
}
return di.FullName ;
}

Related

Try to load a picture from an array of pictures

I'm trying to load a picture into a pictureBox from a string array of pictures I created using Directory.GetFiles(). I believe I am not setting properly setting the picFile correctly.
I've than created a pictureBox_Click event to load subsequent pictures but have not written that event handler
string fileEntries = "";
private void showButton_Click(object sender, EventArgs e)
{
// First I want the user to be able to browse to and select a
// folder that the user wants to view pictures in
string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
folderPath = folderBrowserDialog1.SelectedPath;
}
// Now I want to read all of the files of a given type into a
// array that from the path provided above
ProcessDirectory(folderPath);
// after getting the list of path//filenames I want to load the first image here
string picFile = fileEntries;
pictureBox1.Load(picFile);
}
public static void ProcessDirectory(string targetDirectoy)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectoy);
}
// event handler here that advances to the next picture in the list
// upon clicking
}
If I redirect the string array to the Console I see the list of files in that directory but it also has the full path as part of the string - not sure if that is the issue.
string[] fileEntries = ProcessDirectory(folderPath);
if (fileEntries.Length > 0) {
string picFile = fileEntries[0];
pictureBox1.Load(picFile);
}
You have fileEntries declared twice.
public static string[] ProcessDirectory(string targetDirectoy) {
return Directory.GetFiles(targetDirectoy);
}
Now I want to read all of the files of a given type into a
array that from the path provided above
So you have to change the signature of the method ProcessDirectory to return a string affy that includes all the picture files, you can use the search pattern to get files with specific extension as well. You can use the following signature:
public static string[] ProcessDirectory(string targetDirectoy)
{
return Directory.GetFiles(targetDirectoy,"*.png");
}
after getting the list of path//filenames I want to load the first image here
So you can call the method to get all files in that specific directory with specific extensions. And then load the first file to the picturebox if the array having any files, you can use the following code for this:
var pictureFiles = ProcessDirectory(folderPath);
if (pictureFiles.Length > 0)
{
// process your operations here
pictureBox1.Load(pictureFiles[0]);
}

how to stop Directory.CreateDirectory creating parents?

I know that Directory.CreateDirectory actually creates parents, so how can I STOP this from happening? i.e. is there a mode that I can utilise like a stricter way of doing so, the reason is that I have a watch program watching the parent top tree dir and it goes beserk if Directory.CreateDirectory makes more than one dir at a time.
Is there an equivalent to Directory.CreateDirectory which will NOT make parents?
Do you understand what for you need such method? It seems like you don't want to create all folders needed to create your target folder, like: C:\this\is\your\path\TargetFolder
In this case you can just do the following:
const string path = #"C:\this\is\your\path";
if (Directory.Exists(path))
{
Directory.CreateDirectory(Path.Combine(path, "TargetDirectory"));
}
If you have other purpose for that method, please help us to understand which one
List<string> missingDirectories = null;
private void MakeParents(string path)
{
missingDirectories = new List<string>();
missingDirectories.Add(path);
parentDir(path);
missingDirectories = missingDirectories.OrderBy(x => x.Length).ToList<string>();
foreach (string directory in missingDirectories)
{
Directory.CreateDirectory(directory);
}
}
private void parentDir(string path)
{
string newPath = path.Substring(0, path.LastIndexOf(Path.DirectorySeparatorChar));
if (!Directory.Exists(newPath))
{
missingDirectories.Add(newPath);
parentDir(newPath);
}
}
this does it, the issue is that if you want to "gently" roll up the paths one dir at a time making them, something like this is the only way you can do it :/

Delete files, copy the same named files from another folder C#

I have several issues within a windows forms application. So far, I have managed to loop though a folder and display the reuslts in a text box. Once these have returned, the user can check the results and the error files can be removed using the following;
private void button2_Click(object sender, EventArgs e)
{
foreach (string file in Directory.GetFiles(#"\\" + textBox1.Text + #"\\d$\\NSB\\Coalition\\EDU", "*.err").Where(item => item.EndsWith(".err")))
{
File.Delete(file);
}
}
What I want to do now, after the error files have been removed, is copy the same files from a backup folder (the only difference in the filenames is the file extention) I am using a seperate button for this action. Any help on this final step would be greatly appreciated.
Use Path class to get File names without extensions, combine paths and more, as an example:
StringCollection filesToBeReplaced = new StringCollection();
private void button2_Click(object sender, EventArgs e)
{
foreach (string file in Directory.GetFiles(#"\\" + textBox1.Text + #"\\d$\\NSB\\Coalition\\EDU", "*.err").Where(item => item.EndsWith(".err")))
{
//Now you have file names without extension
filesToBeReplaced.Add(Path.GetFileNameWithoutExtension (file));
File.Delete(file);
}
}
private void CopyGoodFilesFromSource()
{
foreach(string fileName in filesToBeReplaced)
{
string sourceFilePath = Path.Combine("YOUR FOLDER FOR GOOD FILES",
Path.ChangeExtension(fileName,"Your Extension")) ;
string destinationPath = Path.Combine("Destination Folder",
Path.ChangeExtension(fileName, "Your Extension in destination folder");
File.Copy(sourceFilePath , destinationPath, true);
}
}

Copy entire directory with button from two dynamic locations

Okay, I have a button (button1) which I want to copy the static directory to the chosen directory. Essentially I have textbox1 in which different numeric values are added which correlate with different directories. I have a dictionary that sets the string to mapping which links to codes from textbox2 to the path of the origination folder. . This determines where we copy our data from. I want this data to then be copied into the folder selected in textbox2 through the folderBrowserDialog1.ShowDialog(); command. how to i create the dictionary and where do i put it for textbox1, and how do i then get the button to take whatever is in textbox1 and copy the entire directory to textbox2?
private Dictionary<string, string> mapping = new Dictionary<string, string>
{
{ "111", #"C:\Program Files\Example" },
{ "112", #"C:\Program Files\Example2" },
{ "113", #"C:\Program Files\Example3" },
};
public static string[] GetFiles(string mapping);
public static void Copy(string sourceFileName, string destFileName);
private void button2_Click(object sender, EventArgs e)
{
string destination = textBox1.Text;
foreach (var f in Directory.GetFiles(mapping))
{
File.Copy(Path.Combine(mapping, f)); destination;
}
}
Here is an answeer to "How copy an entire directory of files":
Use Directory.GetFiles() (see documentation) to get a list of all files in a directory.
Then use File.Copy() (see documenation) to copy a single file:
foreach(var f in Directory.GetFiles(srcPath))
{
File.Copy(Path.Combine(srcPath, f), dstPath);
}
EDIT
Directory.GetFiles() requires a path:
private void button2_Click(object sender, EventArgs e)
{
string destination = textBox1.Text;
string srcdir = mapping["111"];
foreach(var f in Directory.GetFiles(srcdir))
{
string srcpath = Path.Combine(srcdir, f)
File.Copy(srcpath, destination);
}
}
I'm not 100% sure I understood the details of your question, as the uses of TextBox1 and TextBox2 don't seem consistent, but here's what I read:
TextBox1 has the codes that the dictionary maps to a source directory.
TextBox2 has the path (from the dialog box) to the destination directory.
If that is correct, you're close. Some things to note:
I'm not sure why you have these two lines. They look like method definitions, but there's no implementation. I think you can remove them and use the equivalent System.IO calls:
public static string[] GetFiles(string mapping);
public static void Copy(string sourceFileName, string destFileName);
Directory.GetFiles(mapping) won't work, because mapping is a Dictionary<string, string>, not a string. You need to select the corresponding value (path) based on the key (numeric code) from TextBox1 and use that in the Directory.GetFiles() method.
File.Copy(Path.Combine(mapping, f)); destination; is an incorrect syntax and won't compile (should be File.Copy(Path.Combine(mapping, f), destination);. Additionally, you don't need to combine the source path and filename for the first argument, as GetFiles returns the path along with the filename (including extension). You will need to get the filename alone and combine it with the sourece path for the destination file, however. You can use Path.GetFileName to do this.
Try this code below - it addresses the issues noted above, with the assumption being that textBox1 is the source in mappings and textBox2 is the destination from the dialog window:
private void button2_Click(object sender, EventArgs e)
{
string source = textBox1.Text
string destination = textBox2.Text;
if (mappings.ContainsKey(source))
{
foreach (var f in Directory.GetFiles(source))
{
File.Copy(f, Path.Combine(destination, Path.GetFileName(f)));
}
}
else
{
// No key was found, how you handle it will be dictated by the needs of the application and/or users.
}
}
The above code does the following:
Gets the numeric value for the path of the source directory. This should correspond to one of the keys in the dictionary.
Gets the path for the destination directory based on the user selected value from the dialog box.
Checks to see if the key from textBox1 is present in the directory.
If it is, it gets the corresponding value for that key, which is the path for the source directory.
Next, it loops through the files in the specified source directory, copying each one in turn to the destination directory. Note that f (the file) is used as the source file for the first argument (as it contains the path as well, as Directory.GetFiles() returns both the path and the filename), and the destination directory is combined with the filename (retrieved by a call to Path.GetFileName). If f alone was used in the Path.Combine() method, you'd wind up with sourcePath\originalPath\filename.
If the key wasn't found, you ignore it or do something with it.
Again, the above code is based on my understanding of your question. If my understanding was less than correct, the principles I outlined should still be able to assist you in resolving the issue.
** EDIT **
Per the comments below, it sounds like all you need to do is flip the assignments for source and destination. textBox2 will contain the code that corresponds to a key in the mappings directory, which will give you the path of the source directory. textBox1 will contain the destination path. Like this:
string source = textBox2.Text
string destination = textBox1.Text;
The rest of the code stays the same.

Move File To Sub-Directories

Moving files is easy & clear in .NET what gets me is how to move to a sub-directory For example, let's say I have a file in my source destination called Joe_2.mp3, and I need to move it to destination directory and to the most recently modified sub-folder if one exists. If it does not just move it straight into the destination directory. How would I 1st check for sub-directories & if they exist find the most recently modified one and move the source file their?
This is what I was using when it was just a straight move from directory1 to directory2
private string source = #"C:\\First\\";
private string unclear = #"C:\\Second\\";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo FirstCheck = new DirectoryInfo(#"C:\\First\\");
DirectoryInfo SecondCheck = new DirectoryInfo(#"C:\\Second\\");
IEnumerable<string> list1 = FirstCheck.GetFiles("*.*").Select(fi => fi.Name);
IEnumerable<string> list2 = SecondCheck.EnumerateFiles("*", SearchOption.AllDirectories).Select(fi => fi.Name);
IEnumerable<string> missing = list1.Except(list2);
foreach (var file in missing)
{
var subdi = new DirectoryInfo(SecondCheck.ToString());
var direcetories = subdi.EnumerateDirectories().OrderBy(d => d.CreationTime).Select(d => d.Name).ToList();
File.Move(source, unclear);
}
}
Use Directory.GetDirectories to get the paths of all the subdirectories, then use the Directory.GetCreationTime to get the info you need. Then you can just sort them and take the minimal value that matches your criteria.

Categories