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.
Related
I need to retrieve paths of files and folders currently copied into the clipboard, is this possible in C#?
So let's say I do Ctrl + C a folder. That folder will go to clipboard, I need a way to extract the path to that folder. Same goes for copied files.
I'm developing a file server, I already can send files and folders: all I need is to provide a list of paths to the function.
Microsoft supplies some samples about it:
Have a look at: DragDropOpenTextFile
This is the method used to check it there is a file copied in the clipboard:
// If the data object in args is a single file, this method will return the filename.
// Otherwise, it returns null.
private string IsSingleFile(DragEventArgs args)
{
// Check for files in the hovering data object.
if (args.Data.GetDataPresent(DataFormats.FileDrop, true))
{
var fileNames = args.Data.GetData(DataFormats.FileDrop, true) as string[];
// Check for a single file or folder.
if (fileNames?.Length is 1)
{
// Check for a file (a directory will return false).
if (File.Exists(fileNames[0]))
{
// At this point we know there is a single file.
return fileNames[0];
}
}
}
return null;
}
You get a DragEventArgs from the Drop event handler of your control.
private void EhDrop(object sender, DragEventArgs args)
{
// Mark the event as handled, so Control's native Drop handler is not called.
args.Handled = true;
var fileName = IsSingleFile(args);
if (fileName != null)
{
// Do something.
}
}
Ok got it to work myself, Clipboard.GetFileDropList() gets you both files and folders paths, what a neat little function!
var unparsedFilesList = Clipboard.GetFileDropList();
foreach(var filePath in unparsedFilesList)
{
MessageBox.Show(filePath);
}
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]);
}
I have some code that is extracting a file to a directory. In the code below Global.fullpath is the full path to the file its self where as Global.path is the path to the directory. This code works:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
AppendTextBox("Extracting Files...\r\n");
ZipFile.ExtractToDirectory(Global.fullPath, Global.path);
}
However I am trying to do an overwrite if any files exist so I have this code which doesn't seem to extract anything even when there are no existing files:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
AppendTextBox("Extracting Files...\r\n");
using (ZipArchive archive = ZipFile.OpenRead(Global.fullPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
AppendTextBox("Extracting file: " + entry.FullName + "...\r\n");
entry.ExtractToFile(Path.Combine(Global.path, entry.FullName), true);
}
}
}
Based on the comments, if you're trying to extract a directory ExtractToFile() is not going to do what you expect. Directories can't be easily overwritten like files. I think you have two options:
Check if the directory specified by FullName exists, and delete it before writing.
Check if the directory specified by FullName exists, and then rename your folder you're going to write something like FullName = FullName + "_Copy";
Make sure you check if the combined path is a valid filename. The ExtractToFile method expects a path that ends with the filename, and some Zip archives can contain folders. In such a case, the entry.FullName property results in an invalid path.
I have a dirctory like this "C:/Documents and Settings/Admin/Desktop/test/" that contain a lot of microsoft word office files. I have a textBox in my application and a button. The file's name are like this Date_Name_Number_Code.docx. User should enter one of this options, my purpose is to search user entry in whole file name and find and open the file.
thank you
string name = textBox2.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
MessageBox.Show("Match Found : " + file);
}
}
G'day,
Here's the approach I used. You'll need to add a textbox (txtSearch) and a button (cmdGo) onto your form, then wire up the appropriate events. Then you can add this code:
private void cmdGo_Click(object Sender, EventArgs E)
{
// txtSearch.Text = "*.docx";
string[] sFiles = SearchForFiles(#"C:\Documents and Settings\Admin\Desktop\test", txtSearch.Text);
foreach (string sFile in sFiles)
{
Process.Start(sFile);
}
}
private static string[] SearchForFiles(string DirectoryPath, string Pattern)
{
return Directory.GetFiles(DirectoryPath, Pattern, SearchOption.AllDirectories);
}
This code will go off and search the root directory (you can set this as required) and all directories under this for any file that matches the search pattern, which is supplied from the textbox. You can change this pattern to be anything you like:
*.docx will find all files with the extention .docx
*foogle* will find all files that contain foogle
I hope this helps.
Cheers!
You can use Directory.GetFiles($path$).Where(file=>file.Name.Contains($user search string$).
Should work for you.
You can use the Directory.GetFiles(string, string) which searches for a pattern in a directory.
So, for your case, this would be something like:
string[] files =
Directory.GetFiles("C:/Documents and Settings/Admin/Desktop/test/",
"Date_Name_Number_Code.docx");
Then look through the files array for what you are looking for.
if you need info about the files instead of content:
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
I need some help in renaming some images in a directory located at /images/graphicsLib/.
All image names in /graphicsLib/ have naming convention that looks like this:
400-60947.jpg. We call the "400" part of the file the prefix and we call the "60957" part the suffix. The entire file name we call the sku.
So if you saw the contents of /graphicLib/ it would look like:
400-60957.jpg
400-60960.jpg
400-60967.jpg
400-60968.jpg
402-60988.jpg
402-60700.jpg
500-60725.jpg
500-60733.jpg
etc...
Using C# & System.IO , what is an acceptable way to rename all image files base on the prefix of the file name? Users need to be able to enter in the current prefix, see all images in the /graphicsLib/ that match, then enter in the new prefix to have all those files renamed with the new prefix. Only the prefix of the file gets renamed, the rest of the file name needs to be unchanged.
What I have so far is:
//enter in current prefix to see what images will be affected by
// the rename process,
// bind results to a bulleted list.
// Also there is a textbox called oldSkuTextBox and button
// called searchButton in .aspx
private void searchButton_Click(object sender, EventArgs e)
{
string skuPrefix = oldSkuTextBox.Text;
string pathToFiles = "e:\\sites\\oursite\\siteroot\\images\graphicsLib\\";
string searchPattern = skuPrefix + "*";
skuBulletedList.DataSource = Directory.GetFiles(pathToFiles, searchPattern);
skuBulletedList.DataBind();
}
//enter in new prefix for the file rename
//there is a textbox called newSkuTextBox and
//button called newSkuButton in .aspx
private void newSkuButton_Click(object sender, EventArgs e)
{
//Should I loop through the Items in my List,
// or loop through the files found in the /graphicsLib/ directory?
//assuming a loop through the list:
foreach(ListItem imageFile in skuBulletedList.Items)
{
string newPrefix = newSkuTextBox.Text;
//need to do a string split here?
//Then concatenate the new prefix with the split
//of the string that will remain changed?
}
}
You could look at string.Split.
Loop over all files in your directory.
string[] fileParts = oldFileName.Split('-');
This will give you an array of two strings:
fileParts[0] -> "400"
fileParts[1] -> "60957.jpg"
using the first name in your list.
Your new filename then becomes:
if (fileParts[0].Equals(oldPrefix))
{
newFileName = string.Format("(0)-(1)", newPrefix, fileParts[1]);
}
Then to rename the file:
File.Move(oldFileName, newFileName);
To loop over the files in the directory:
foreach (string oldFileName in Directory.GetFiles(pathToFiles, searchPattern))
{
// Rename logic
}
Actually you should iterate each of the files in the directory and rename one by one
To determine the new file name, you may use something like:
String newFileName = Regex.Replace("400-60957.jpg", #"^(\d)+\-(\d)+", x=> "NewPrefix" + "-" + x.Groups[2].Value);
To rename the file, you may use something like:
File.Move(oldFileName, newFileName);
If you are not familiar with regular expressions, you should check:
http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx
And download this software to pratice:
http://www.radsoftware.com.au/regexdesigner/