I want to read 2 excel files from the same directory and store their full paths in two different variables.
For example,
C:\\Users\\User\\Desktop\\Folder\\File1.xlsx - First value
C:\\Users\\User\\Desktop\\Folder\\File2.xlsx - Second value
I am taking a string array for this but it is not working.
Please help.
I have done the following:
string[] location = new string[2];
int i = 0;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
this.openFileDialog1.Filter = "Excel|*.xlsx;*.xlxm;*.xls | All files (*.*)|*.*";
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "Select Excel Files";
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
location[i] = Path.GetDirectoryName(file);
i++;
}
}
The only thing I can see wrong with your code is you are creating a local instance of OpenFileDialog and then trying to reference it as if it were a class member field.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
this.openFileDialog1.Filter = "Excel|*.xlsx;*.xlxm;*.xls | All files (*.*)|*.*";
Get rid of this.
Your code is very risky of crashing in case user does select more than one file. I see no reason why to set the array size of "location" directly to two.
I recommend you to check the comment from Alex K. The .FileNames -property of the dialog already is an array. And getting the directory, will then be the same for all (like Crowcoder wrote).
I assume, what you need at the end is this:
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Excel|*.xlsx;*.xlxm;*.xls | All files (*.*)|*.*";
openFileDialog1.Multiselect = true;
openFileDialog1.Title = "Select Excel Files";
DialogResult dr = openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
string[] location = openFileDialog1.FileNames;
// do something
}
And if in case, you need the directory, do this:
string[] location = openFileDialog1.FileNames.Select(x => Path.GetDirectoryName(x)).ToArray()
Related
I have created a software, which save some Information in an Excel File. The software has two possibilities:
To select the folder and then the software will create an Excel File with random name and there will save the data , or
To select an existed Excel File which is created from the user and there will save the data.
How to create a ONE ShowDialog to ask the user do you want to choose the folder or the file?!
Code that I have used to choose a Folder:
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
textBox3.Text = fbd.SelectedPath;
}
}
Code that I have used to choose a File:
OpenFileDialog excelFilename = new OpenFileDialog();
if (excelFilename.ShowDialog() == DialogResult.OK)
{
textBox3.Text = excelFilename.FileName;
}
Maybe something like this?:
MessageBoxResult result = MessageBox.Show("Ask user what he wants to do", "", MessageBoxButton.YesNo);
string path = null;
//MessageBoxResult.Yes means File, .No means Folder
if (result == MessageBoxResult.Yes)
{
//File-Picker
OpenFileDialog filePicker = new OpenFileDialog()
{
FileName = "Excel File",
DefaultExt = ".xls",
Filter = "Excel Document | *.xls"
};
if (filePicker.ShowDialog() == true)
{
path = filePicker.FileName;
}
}
else if (result == MessageBoxResult.No)
{
//Folder-Picker
CommonOpenFileDialog folderPicker = new CommonOpenFileDialog()
{
IsFolderPicker = true,
Multiselect = false
};
path = Path.Combine(folderPicker.FileName, DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss"));
//Create file in folder
File.Create(path);
}
if (path != null)
{
// Do something with path (file user selected/program created)
}
Make sure you have the using System.Windows, using Microsoft.Win32; and using System.IO; using's at the beginning of your program.
You also have to add the WindowsAPICodePack library to your project to use the folder-picker. You can do that with the NuGet manager. Here's the link to the library: WindowsAPICodePack - 1.1.1
I have a method that saves the text from a text box into a txt file but I get an System.IO.IOException error every time I back out of the SaveFileDialog.
static OpenFileDialog ofd = new OpenFileDialog();
static SaveFileDialog sfd = new SaveFileDialog();
static String cp;
private void SaveClass() {
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK) {
cp = sfd.FileName;
File.Create(cp);
File.WriteAllLines(#cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
}
Visual Studio highlights the code that starts with "File.WriteAllLines" and says that's where I'm getting the error. Thanks.
Exact error message:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\ktfjulien\Documents\poop.txt' because it is being used by another process.
EDIT:
Thank you, I no longer get the error message but everything I save into the text box is written onto one line, regardless if the text is delimited by new lines or not.
You do not need to do File.Create(cp); to write to a file. This is the cause of the error. Instead, directly do:
cp = sfd.FileName;
FileStream fs = File.OpenWrite(cp);
And if you want to use the StreamWriter instead of FileStream, use the FileStream as the input for your StreamWriter
StreamWriter sw = new StreamWriter(fs);
Or, you could also directly use File.WriteAllLines as you show - don't use the File.Create:
if (sfd.ShowDialog() == DialogResult.OK) {
cp = sfd.FileName;
//File.Create(cp); //remove this
File.WriteAllLines(#cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
When you are creating file using File.Create() this file is already used by File.Create() you need close that file before use another place so before writing text to the file close file writer
var file = File.Create(cp);
file.Close();
complete working solution
static OpenFileDialog ofd = new OpenFileDialog();
static SaveFileDialog sfd = new SaveFileDialog();
static String cp;
private void SaveClass()
{
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
cp = sfd.FileName;
var file = File.Create(cp);
file.Close();
File.WriteAllLines(#cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
}
You have no need to create the file, File.WriteAllLines will do it for you (or clear up the file if it exists):
private void SaveClass() {
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
File.WriteAllLines(sfd.FileName, StudentTextBox.Text
.Split(new String[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries));
}
What I have here is the user select a folder full of .txt files from a external drive and a dummy file is made with the filename to a local folder.
I have 2 questions regarding the code below.
How do I verify that the user select a specific folder?
How do I remove the .txt extension? The code copies the file name and creates the files but its labeled "text.txt.png" but I need it to read "text.png".
int g;
private void folderSelect()
{
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.RootFolder = Environment.SpecialFolder.MyComputer;
folder.ShowNewFolderButton = false;
folder.Description = "Select Folder";
if (folder.ShowDialog() == DialogResult.OK)
{
DirectoryInfo files = new DirectoryInfo(folder.SelectedPath);
FileInfo[] textFiles = files.GetFiles("*.txt");
while (g < textFiles.Length)
{
if (g <= textFiles.Length)
{
File.Create("path/" + (textFiles[g].Name + ".png"));
g++;
}
else
{
break;
}
}
}
Note: I tried using Path.GetFileNameWithoutExtension to remove the extension but Im not sure if i was using it correctly.
Any help would be appreciated. Thank you in advance.
const string NEW_PATH = "path/";
if (!Directory.Exists(NEW_PATH))
Directory.CreateDirectory(NEW_PATH);
const string PATH_TO_CHECK = "correctpath";
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.RootFolder = Environment.SpecialFolder.MyComputer;
folder.ShowNewFolderButton = false;
folder.Description = "Select Folder";
if (folder.ShowDialog() == DialogResult.OK)
{
string pathPastDrive = folder.SelectedPath.Substring(Path.GetPathRoot(folder.SelectedPath).Length).ToLower();
// Here it depends on whether you want to check (1) that the path is EXACTLY what you want,
// or (2) whether the selected path just needs to END in the path that you want.
/*1*/ if (!pathPastDrive == PATH_TO_CHECK)
/*2*/ if (!pathPastDrive.EndsWith(PATH_TO_CHECK))
return; // or you can throw an exception if you want
foreach (string textFile in Directory.GetFiles(folder.SelectedPath, "*.txt"))
File.Create(NEW_PATH + Path.GetFileNameWithoutExtension(textFile) + ".png");
}
You can use GetFileNameWithoutExtension, and it makes it pretty easy.
Also, if you're already sure that your new folder exists, then you can elide the first three lines and replace NEW_PATH with "path/" in the last line.
To see the returned path just use the SelectedPath property, then you can compare it to whatever you had in mind. The # before the path just means I don't have to escape any characters, it's the same as "C:\\MyPath".
FolderBrowserDialog folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
if (folder.SelectedPath == #"C:\MyPath")
{
// DO SOMETHING
}
}
You already hit the nail on the head about the file name without extension, change this line:
File.Create("path/" + (textFiles[g].Name + ".png"));
To this:
File.Create("path/" + (Path.GetFileNameWithoutExtension(textFiles[g].Name) + ".png"));
Edit:
To get the folder name you already have the DirectoryInfo object so just use that:
DirectoryInfo files = new DirectoryInfo(folder.SelectedPath);
string folderName = files.Name;
I have a WPF application in which i have this method:
public static string getFile(List<string> extensions)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
string ext = "files (", filter = "";
foreach (string s in extensions)
{
ext += s + ",";
filter += "*." + s + ";";
}
ext += ")";
dlg.Filter =ext+"|"+ filter;
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
return dlg.FileName;
}
else return null;
}
I need to add another simple method which returns a folder path in which i will save new file.
How can i do this?
What is the best way to do it?
SaveFileDialog is what you need. From MSDN link:
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
}
I'd suggest having a look at the free Ookii Dialogs for WPF. I've used it on commercial projects in the past and it's always worked really well. Native support for WPF obviously but also has a lot of options for customization and provides more consistency across different versions of Windows.
I have a set of files written to a temporary directory which I want to display to the user. In this instance I wish them to be able to select a file and then have the option of saving it. Is there a decent control in C# for doing this?
I think you could use OpenFileDialog and FolderBrowserDialog for example:
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.InitialDirectory = "c:\\";//your temp directory path
dialog.Title = "Select files to move/copy";
if (dialog.ShowDialog() == DialogResult.OK)
{
string[] files = dialog.FileNames;
using (FolderBrowserDialog save = new FolderBrowserDialog())
{
save.Description = "Select location to save files";
if (save.ShowDialog() == DialogResult.OK)
{
foreach (string file in files)
{
FileInfo finfo = new FileInfo(file);
File.Move(file, save.SelectedPath + finfo.Name);
}
}
}
}
}
Would a simple Open File Dialog be sufficent? You can restrict it to only show the files with your temporary extension. OpenFileDialog in C# gives some examples of use.