I use OpenFileDialog to search for a specific file. When the user chooses the file, I want to store that path in a variable. However, these doesn't seem to be an option for this within OpenFileDialog?
Does anybody know how to do this?
Thanks.
Edit: This is Winforms, and I don't want to save the path inclusive of the filename, just the location where the file is.
If you are using WinForms, use the FileName property of your OpenFileDialog instance.
On WinForms:
String fileName;
OpenFileDialog ofd = new OpenFileDialog();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.Ok) {
fileName = ofd.FileName;
}
//getting only the path:
String path = fileName.Substring(0, fileName.LastIndexOf('\\'));
//or easier (thanks to Aaron)
String path = System.IO.Path.GetDirectoryName(fileName);
This will retrieve your path based on the FileName property of the OpenFileDialog.
String path = System.IO.Path.GetDirectoryName(OpenFileDialog.FileName);
Instead of copy pasting answers from MSDN I'll just link to them.
MSDN documentation on Forms OpenFileDialog.
MSDN documentaiton on WPF OpenFileDialog.
Please try to look for a answer before posting questions.
You store the path ... somewhere else!
What I usually do is create a user-scoped configuration variable.
Here's a sample of its use:
var filename = Properties.Settings.Default.LastDocument;
var sfd = new Microsoft.Win32.SaveFileDialog();
sfd.FileName = filename;
/* configure SFD */
var result = sfd.ShowDialog() ?? false;
if (!result)
return;
/* save stuff here */
Properties.Settings.Default.LastDocument = filename;
Properties.Settings.Default.Save();
To save just the directory, use System.IO.Path.GetDirectoryName()
After the dialog closes there should be a file path (or something similar) property on the OpenFileDialog object, it will store whatever file path the user entered.
Try FileName. Or FileNames if you allow multiple files to be selected(Multiselect=true)
Related
I am trying to bypass the save dialog box when using the SaveFileDialog class. I want to be able to write to a document without having to prompt a user to decide if they want to save or not, the file should automatically save when they click a button.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.RestoreDirectory = true ;
saveFileDialog1.InitialDirectory = #"C:\";
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// Code to write the stream goes here.
}
I have tried removing the if statement as well as using...
saveFileDialog1.CreatePRompt = false;
Nothing seems to work... Any ideas?
I think you want to bypass the overwrite prompt dialog.
In this case you can use
saveFileDialog1.OverwritePrompt = false;
Otherwise, you don't need a SaveFileDialog and you can save your stream without using it.
I found my answer. The question I asked was actually two it seems. The first was how to bypass SaveFileDialog, I wanted to use saveFileDialog because it can remember the last folder it accessed and opens to that folder when performing a read/save. That being said I implemented this...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
This will set Directory to the location of my executable.
Next I got rid of SaveFileDialog and just wrote to a file without ever prompting the user.
Thanks for all the pointers and ideas!
The end result ended up...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
using(System.IO.StreamWriter file = new System.IO.StreamWriter(Directory, false))
{
// File contents
}
Works perfectly for what I need it for.
If you want to save but you need the user to pick a filename, I would use this:
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//setup properties of Dialog
bool filenamepicked = false;
while (!filenamepicked)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//Save file
filenamepicked = true;
}
else
{
MessageBox.Show("You have to use a file name.");
}
}
I have problem with InitialDirectory path i used part of code shown below. OpenDialog always show directory where i open file last time but i couldn't set new relative path.. I tried set absolute path but it didn't work also.
private static string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
public static string OpenDialog()
{
// Create OpenDialog
var dlg = new Microsoft.Win32.OpenFileDialog();
// initial directory for OpenFileDialog need fix
if(Directory.Exists(path))
{
dlg.InitialDirectory = path;
}
dlg.RestoreDirectory = true;
In your example, 'path' is being set to your .exe, which will cause if (Directory.Exists(path)) to fail, therefore, the dialog will open to the last known good directory, because InitialDirectory will not be set to the value that you want. Try simply hard-coding a known good directory path first. Or you could do something like this to fix it:
path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
In my form I have a button that launches the SaveFileDialog module. Then when I load a file, I want to save the path as a string and put that text into a text box on the form. I'm not sure how to do this, or even where to start?
Well the problem with your question is that you say when you "load a file", but you cannot load a file from the SaveFileDialog module. However, if you are opening a file via the OpenFileDialog module, then you are able to use this solution to get the directory path of the file you just loaded:
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(openFileDialog1.FileName);
if(!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}
Otherwise, if you are wanting to get the file path of whatever file you saved originally, you can use pretty much the same solution to get the directory path:
if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(saveFileDialog1.FileName);
if (!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}
I want to create a browse (OpenFile Dialog) Button to search my local drive and then write out the selected file name (not the full path ) to a TextBox. It should show Only .dat extension files.
I am using Visual Studio 2008
Any help much appreciated!
Next time you ask anything, show some examples of what you have tried please.
private string GetDatFileName()
{
// Create Open File Dialog with the correct filter
using (OpenFileDialog ofd = new OpenFileDialog()) {
ofd.Filter = "dat-file (*.dat) | *.dat";
string fileNameAndFolder = "";
string fileName = "";
// Get file plus folder.
if (ofd.ShowDialog() == DialogResult.OK)
{
fileNameAndFolder = ofd.FileName;
// Split folder and filename
fileName = Path.GetFileName(fileNameAndFolder);
}
// Return the fileName;
return fileName;
}
}
What I have done here is create an OpenFileDialog and set its filter to the required "dat"-format. Only .dat-files will show up in the browserdialog.
Next, you show the dialog and check if the result is OK. If the result is, you will get the full filename (with folder) into a variable. All thats left then, is to get the filename from fileNameAndFolder.
I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension.
In plain english I would like to know how to:
-Create a .dat file
-Write to it
-And save the file using SaveFileDialog
There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn.
The following code is what I have at the moment. Basically it opens a SaveFileDialog window with a blank File: section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
Pages that I've been looking at:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
Note that the SaveFileDialog only yields a filename but does not actually save anything.
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
Use the filename you are getting from the SaveFileDialog and do the following:
File.WriteAllText(filename, contents);
That's all if you intend to write text to the file.
You can also use:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}