Currently, I have a browser dialog that opens and allows the user to select a folder in which doc / docx files will be merged into one file. At the moment, it is rigged up to merge files once the 'DialogResult.ok' button is dismissed in the browser dialog. as shown below:
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"C:\";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
}
private void combineButton_Click(object sender, EventArgs e)
{
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + AllDocFolder.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
the issue i am having is that i want the 'combineButton' to merge the documents as opposed to the 'DialogResult.ok'. When i copy the lines:
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
into the combineButton area, i get an error saying 'the name 'selectedFolder' does not exist in the current context'. This may be a stupid question, but is there a quick way to remedy this?
As far as I understand your problem, you want to split the folder selection and the merging of the documents, right?
So you could put the information about the target directory into a class variable:
public class MyForm
{
private string[] _sourceFiles;
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"C:\";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
_sourceFiles = Directory.GetFiles(selectedFolder, "*.doc");
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (_sourceFiles != null && _sourceFiles.Length > 0)
{
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(_sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + _sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
Related
In my company it is common to name files in the following manner: 210808_Filename.extension
Unfortunately both of these ways to get the filename failed: Path.GetFileName() and OpenFileDialog.SafeFileName. In the path itself the underscores exist, but in the filename they get removed.
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
string strCheck = "";
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
strConfigPath1 = openFileDialog1.FileName;
if (strConfigPath1.Length > 6)
{
strCheck = strConfigPath1.Substring(strConfigPath1.Length - 6);
}
if (strConfigPath1 == "" || strCheck != ".gcode")
{
MessageBox.Show("Selected file has to be a GCode file.");
}
else
{
lblSelectedDocument.Content = System.IO.Path.GetFileName(string);
}
}
I know it may not be a well programmed code due to the fact I am bloody new to programming. Sorry for that.
Here's a straightforward way to set the contents of the label, based on the file that the user selects:
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
string chosenFilename = openFileDialog.FileName;
if (Path.GetExtension(chosenFilename).ToLower() == ".gcode")
{
lblSelectedDocument.Content = "Valid file. You selected " + chosenFilename;
}
else
{
lblSelectedDocument.Content = "Invalid file - not a .GCODE file. You selected " + chosenFilename;
}
}
else
{
lblSelectedDocument.Content = "You did not select a file.";
}
}
If the user doesn't select a file, we just set the label to be You did not select a file.
If the user did select a file, we check if the file extension is our intended extension. The check is case-insensitive, so .GCODE, .GcOdE, .gcode (etc) will all work. If the user selected a gcode file, the label says the filename is valid and shows the filename.
If the file extension doesn't match, the user must have selected an invalid file. When this occurs we tell them the filename is invalid and show the filename.
I am new to C#. I am working on a Windows Form that should do the following:
Browse files on local drive
Allow the user to select files
List the selected files in a listBox
Allow the user to input a new file name and, when they click the rename button, it renames the selected file in the ListBox.
I am not able to do step 4 as the new text is changed in the listBox but the actual file name is still the same in folder. How can I do that? I have listed below the Form.cs
Thank you.
public partial class everSupportForm : Form
{
private void buttonSelect_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
var myDialog = new OpenFileDialog();
myDialog.InitialDirectory = #"c:\";
myDialog.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
// + "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" //If you want to add filters for browsing only images.
myDialog.FilterIndex = 1;
myDialog.RestoreDirectory = true;
myDialog.Multiselect = true;
myDialog.Title = "Please Select File(s) to Rename";
if (myDialog.ShowDialog() != DialogResult.OK) return;
{
foreach (var file in myDialog.FileNames)
{
try
{
if ((myStream = myDialog.OpenFile()) != null)
{
using (myStream)
{
outputListBox.Items.Add(System.IO.Path.GetFileName(file));
}
}
}
catch (Exception ex)
{
// Could not load File specifying the causes
MessageBox.Show("Cannot display the File");
}
}
}
}
private void buttonExit_Click(object sender, EventArgs e) => Application.Exit();
// Removes a selected item
private void buttonRemove_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >= 0)
outputListBox.Items.RemoveAt(outputListBox.SelectedIndex);
}
// Clears the listed images ListBox
private void buttonClear_Click(object sender, EventArgs e) => outputListBox.Items.Clear();
private void buttonRename_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >= 0)
outputListBox.Items[outputListBox.SelectedIndex] = newNametextBox.Text;
else MessageBox.Show("There is no Files in the Above list to be Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
First of all, you have a problem here.
You're adding the files names using Path.GetFileName, so you won't have the files paths anymore => you can't rename them.
Solution 1 - Adding the paths to the listbox
You simple remove the Path.GetFileName and in when the rename button is clicked, you use an InputBox to ask the user for the new file name:
N.B: Add a reference to Microsoft.VisualBasic, InputBoxis in the Microsoft.VisualBasic.Interaction namespace.
private void buttonRename_Click(object sender, EventArgs e)
{
if (outputListBox.SelectedIndex >=0)
{
string fileToRename = outputListBox.Items[outputListBox.SelectedIndex].ToString();
string newFileName = InputBox("Please enter the new file's name:", "Rename file", "Default value");
if (!string.IsNullOrEmpty(newFileName))
{
string fileName = Path.GetFileName(fileToRename);
string newFilePath = fileToRename.Replace(fileName, newFileName);
System.IO.File.Move(fileToRename, newFilePath);
outputListBox.Items[outputListBox.SelectedIndex] = newFilePath;
}
}
else
{
MessageBox.Show("There is no Files in the Above list to be Selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Solution 2 -- Keep a seperate list containing the paths
The concept is the same as the first solution, but instead of adding the file paths to your listbox, you add the file names but you keep a seperate list of paths that is synced with your listbox.
Meaning that, if you modify the listbox, modify the list of paths.
After that you can access the file paths using the listbox's SelectedIndex (since they are synced).
I have a "settings" button in one of my programs that will be used to grab a directory that the user wants to work with.
After they select a directory, I'd like to be able to return three pieces of information.
The name of the directory chosen.
The number of files in that directory (just files, not other directories)
A list with the names of every file in the directory.
I have been looking through this page, and I found the GetFiles() method, but I haven't figured out how to get the name of the directory. Any nudge in the right direction is appreciated.
Here's what I have so far.
public void SettingsButton(object sender, RoutedEventArgs e)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(dialog.SelectedPath);
MessageBox.Show("files found" + files.Length.ToString(), "Message");
}
}
I know the code above doesn't return the names of the files, but I know the rough idea on how to do that, I just haven't implemented it yet....so my questions just about storing the directory they chose as a string.
here's an example how you can do this, a simple foreach:
public void SettingsButton(object sender, RoutedEventArgs e)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(dialog.SelectedPath);
string resultStr = string.Empty;
foreach (String item in files)
{
resultStr += item.ToString() + "\n";
}
MessageBox.Show("path:" + dialog.SelectedPath + "\n" +
"files: " + files.Count().ToString() + "\n" +
resultStr, "Message");
}
}
using System.Windows.Forms;
FolderBrowserDialog() dialog = new FolderBrowserDialog();
DialogResult result = dialog.ShowDialog();
Here result will have the selected folder.
I opened a directory and I read some files in that directory amd made some changes, now I want to save the changes with the same file names at F:\BI\Out\ and keep the original files.
when I added these two lines
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
I was able to save the files under the new folder\Out,
but when I opened them I found that only one file is changed correctly and all the other files the old words are replace by blank space not by the new words.
Can anyone help me Thanks
string text = "";
string[] files;
private void Form1_Load(object sender, EventArgs e)
{
try
{
files = Directory.GetFiles(#"F:\BI\In\", "*.*", SearchOption.AllDirectories);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtEtlPath.Text == "")
{
MessageBox.Show("Please Enter path");
txtEtlPath.Focus();
}
else
{
foreach (string file in files)
{
if (System.IO.File.Exists(file))
{
text = File.ReadAllText(file);
text = text.Replace("Company_Address", txtCompanyAddress.Text + "_BI");
text = text.Replace("Company_Name", txtCompanyName.Text.Trim() + "_BIDW");
text = text.Replace("C:\\BIfolder",cboDrive.Text + txtEtlPath.Text.Trim());
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
}
Within your foreach () loop:
If you want the subfolder structure of the files found, do a replace on the filepath:
var outFilePath = file.Replace(#"F:\BI\In\", #"F:\BI\Out\");
You will need to create the subfolder before you can write the changed file:
new FileInfo(outFilePath)).Directory.Create();
If you don't want the subfolders, you can write directly into the top folder:
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
Writing is simple, just keep in mind there is an optional encoding parameter:
File.WriteAllText(outFilePath, text);
I am trying to set the selected folder in a FolderBrowserDialog control as a variable, so I can use it within another method
The code I have so far is:
private void button18_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//
// The user selected a folder and pressed the OK button.
// We print the number of files found.
//
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
So I could call the selected folder in the control above in a method like this:
Process.Start("test.exe", <Folder Selection Here> );
I started looking at this before I noticed that you had requested the question to be closed. Anyway here's the code should it be useful for someone else.
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
//Choose the default start up folder
string selectedFolder = #"C:\Dev";
//Set that into the dialog
folderBrowserDialog1.SelectedPath = selectedFolder;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
//Grab the folder that was chosen
selectedFolder = folderBrowserDialog1.SelectedPath;
// The user selected a folder and pressed the OK button.
// We print the number of files found.
string[] files = Directory.GetFiles(selectedFolder);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
MessageBox.Show(selectedFolder);
}
}