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.
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 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()
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 just wanted to know how can i give a custom made default location for grabbing the files.
I have uploaded a file to the local database and i have binded the file to the gird also. When i press download its showing an error called "the file is not found in location"
If i copy the particular uploaded files to the specified location i can download it easily.
So i just need to know how can i give a default location so that i can upload and downlaod the file from the same exact location.
snapshot of error: https://imageshack.com/i/ewTrmAI2j
Edited the same below code with custom made folder path. But i dont know why the file is always being asked from bin/debug/ folder. WHy its happening like this. IS there any way i can make changes to this folder.. other than bin/debug/ folder
Codes:
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
//Return if the cell is empty
if (fileName == string.Empty)
return;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
byte[] byteData = File.ReadAllBytes(fileInfo.FullName); - - - - <<<<< ERROR HERE
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
File.WriteAllBytes(saveFileDialog1.FileName, byteData);
byteData = System.Text.Encoding.ASCII.GetBytes(s);
}
}
}
The FileInfo() constructor only works with a full file path. It sounds like you are trying to use the constructor with just a file name, at which point it fails when you try to read the file because its not a valid path. There are a couple possibilities for dealing with this:
Create your own MyFileInfo() class inheriting from FileInfo() and add a constructor that appends your specific path to the filename.
Simply append the path in-line in your code as:
var myPath = #"c:\folder\stuff\";
FileInfo fileInfo = new FileInfo(myPath + fileName);
Normally the path would be setup as a setting in your app.config so you could change it easily if needed.
I found the answer
codes for the binding file path to the gridview and download the file using the file path
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = fileDialog.FileName;
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = strfilename;
}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = File.ReadAllBytes(s);
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}
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.