I am able to open a file dialog, now i want to know how do i get the path of the file in var variable something like
OpenFileDialog fd1 = new OpenFileDialog();
fd1.InitialDirectory = "c:\\";
fd1.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
fd1.FilterIndex = 2;
fd1.RestoreDirectory = true;
so i want in my var something like
var path = #"c:\abc.pdf";
Is it possible
Here it is:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var path = openFileDialog1.FileName;
}
This way you'll get your path to file like:
C:\folder1\folder2\fffffffff...\abc.pdf
Update:
you'll change your "var" into "string" and you'll make your path variable a global variable. here is an example:
private string path;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
path = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(path);
}
you don't need to make your variable a public because you are in the same class!!!
Update:
Think that this will do
AxAcroPDF1.src = path;
The Process.Start should launch a new process to open the pdf file with default client that is Adobe Reader.
You can prompt user with filedialog to get you a file path.
If you want to get some of specific folders you can try
String PersonalFolder =
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
Environment have alot of folders that are specific for machine.
hope it helps
Related
i have multiple folders. they are named by file extension names. (ex:- doc, dwg, jpg....etc) my list box data source have more files.(ex:- abc.dwg, beauty.jpg, arc.doc.....) i want to move doc files to doc folder, jpg files to jpg folder, dwg files to dwg folder...etc
how to do it single button click >>"create folders" button use
List<string> fileNames = null;
List<string> fileExtensions = null;
private void btn_list_Click(object sender, EventArgs e)
{
listBox_ex.Items.Clear();
using (FolderBrowserDialog FBD = new FolderBrowserDialog())
{
if (FBD.ShowDialog() == DialogResult.OK)
{
lbl_path.Text = FBD.SelectedPath;
fileNames = Directory.GetFiles(FBD.SelectedPath).ToList();
fileExtensions = fileNames.Select(item => Path.GetExtension(item)
.Replace(".", "")).Distinct().OrderBy(n => n).ToList();
listBox_name.DataSource = fileNames.Select(f => Path.GetFileName(f)).ToList();
listBox_ex.DataSource = fileExtensions;
}
}
}
private void btn_CreateFolder_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog FBD = new FolderBrowserDialog())
{
if (FBD.ShowDialog() == DialogResult.OK)
{
lbl_pathCreated.Text = FBD.SelectedPath;
fileExtensions.ForEach(item =>
Directory.CreateDirectory(Path.Combine(FBD.SelectedPath, item)));
}
}
}
The short answer is that you would simply call File.Move, and pass the full path to the existing file as the first argument, and the full path and file name for the destination.
You can build the destination path and then move the files like:
foreach (string file in fileNames)
{
// Build the destination path
var destination = Path.Combine(
FBD.SelectedPath, // The root destination folder
Path.GetExtension(file).Replace(".", ""), // The file extension folder
Path.GetFileName(file)); // The file name (including extension)
// Move the file
File.Move(file, destination);
}
i'm stuck with my program in c#. So the user has to press a button to create a random string (working fine) he can then chose to click on the other button. this one opens a filedialog and let him chose a dll file he want to rename into the random string. i can't get it working. it says my dll is already running in another process (wich is not). Any help is greatly appreciated :)
private void btnEncrypt_Click_1(object sender, EventArgs e)
{
// sets a random string to txtEncrypt.text
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog MyOpenFileDialog = new OpenFileDialog();
//filedialog
MyOpenFileDialog.Filter = "dll files (*.dll) |*.dll";//filter
MyOpenFileDialog.Title = "Chose the dll file";
MyOpenFileDialog.InitialDirectory = "C:\\Users\\Gebruiker\\Desktop";
MyOpenFileDialog.FilterIndex = 1;
MyOpenFileDialog.RestoreDirectory = true;
//if ok
if (MyOpenFileDialog.ShowDialog() == DialogResult.OK)
{
strPath = MyOpenFileDialog.FileName;
StreamReader reader = new StreamReader(strPath);
System.IO.File.Move(strPath, "C:\\Users\\Gebruiker\\Desktop\\" + txtEncrypt.Text + ".dll");
}
else //cancel
{
strPath = null;
}
It's because your StreamReader is opening the file so it can't be moved. That line doesn't appear to be doing anything anyway so you can probably remove it. Ideally replace it with
if (System.IO.File.Exists(strPath))
{
System.IO.File.Move(strPath, "C:\\Users\\Gebruiker\\Desktop\\" + txtEncrypt.Text + ".dll");
}
Just comment the initialization of the streem reader line or move it next to the rename line but don't forget to pass the new name
I am trying to open a file by pressing a button (a label to be more exact but it works just the same way)
For some reason when the FileDialog opens and I select the file and press open it doesnt open the file it only closes the FileDialog
private void selectLbl_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = "c:\\";
ofd.Filter = "Script files (*.au3)|*.au3";
ofd.RestoreDirectory = true;
ofd.Title = ("Select Your Helping Script");
if (ofd.ShowDialog() == DialogResult.OK)
{
ofd.OpenFile(); //Not sure if there is supposed to be more here
}
}
ofd.OpenFile();
is returning the content of the file as Stream of bytes like described here. If you want to open the file like you described it, use
if (ofd.ShowDialog() == DialogResult.OK)
{
System.Diagnostics.Process.Start(ofd.FileName);
}
So your selected file starts with the associated application.
ofd.OpenFile() opens the file selected by the user as a Stream that you can use to read from the file.
What you do with that stream depends on what you are trying to achieve. For example, you can read and output all lines:
if (ofd.ShowDialog() == DialogResult.OK)
{
using (TextReader reader = new StreamReader(ofd.OpenFile()))
{
string line;
while((line = t.ReadLine()) != null)
Console.WriteLine(line);
}
}
Or if it is an xml file you can parse it as xml:
if (ofd.ShowDialog() == DialogResult.OK)
{
using(XmlTextReader t = new XmlTextReader(ofd.OpenFile()))
{
while (t.Read())
Console.WriteLine($"{t.Name}: {t.Value}");
}
}
The OpenFileDialog is not a dialog that opens the file. It only communicates with the operator with a dialog that is commonly shown if a program needs to know what file to open. So it is only a dialog box, not a file opener.
You decide what to do if the user pressed ok or cancel:
private void selectLbl_click(object sender, ...)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.InitialDirectory = "c:\\";
ofd.Filter = "Script files (*.au3)|*.au3";
ofd.RestoreDirectory = true;
ofd.Title = ("Select Your Helping Script");
var dlgResult = ofd.ShowDialog(this);
if (dlgResult == DialogResult.OK)
{ // operator pressed OK, get the filename:
string fullFileName = ofd.FileName;
ProcessFile(fullFileName);
}
}
}
if (ofd.ShowDialog() == DialogResult.OK)
{
ofd.OpenFile(); //Not sure if there is supposed to be more here
}
I have a TextBox (txtDocUpload) and a Button. On the clicking of that button, an upload dialogue is opening and after uploading a file I have to save it in a particular folder.
For opening the upload dialogue
private void txtBtnUpload_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
//openFileDialog.DefaultExt = ".txt";
Nullable<bool> result = openFileDialog.ShowDialog();
if (result == true)
{
filename = openFileDialog.FileName;
txtDocUpload.Text = System.IO.Path.GetFileName(filename);
}
}
Clicking save button I have to save, and the code ("File1"is the location where i want to save the file).
string urlpath = "WoDocs";
var path = #"~\" + urlpath + #"\" + WOMaintenance.GetAddressId.IDWorkOrderDetail;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var ext = System.IO.Path.GetExtension(txtDocUpload.Text);
var pathURL=txtDocDescription.Text+ext;
var file1 = System.IO.Path.Combine(path,txtDocDescription.Text + ext);
//docFile1.SaveAs(file1);
Here is a brief example:
private void CopyAFile()
{
var source = new OpenFileDialog();
if (source.ShowDialog().GetValueOrDefault())
{
var dest = new SaveFileDialog();
if (dest.ShowDialog().GetValueOrDefault())
{
File.Copy(source.FileName, dest.FileName);
}
}
}
This should demonstrate that File.Copy does work when you have access to the source and destination locations.
How do I make my application store the last path opened in openFileDialog and after new opening restore it?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
acc_path = openFileDialog1.FileName;
Settings.Default.acc_path = acc_path;
foreach (string s in File.ReadAllLines(openFileDialog1.FileName))
{
accs.Enqueue(s);
}
label2.Text = accs.Count.ToString();
}
This is the easiest way: FileDialog.RestoreDirectory.
After changing Settings you have to call
Settings.Default.Save();
and before you open the OpenFileDialog you set
openFileDialog1.InitialDirectory = Settings.Default.acc_path;
I think it would be enough for you to use SetCurrentDirectory to ste the current directory for the OS. So on the next dialog opening it would pick that path.
Or simply save path into some variable of your application and use
FileDialog.InitialDirectory property.
The following is all you need to make sure that OpenFileDialog will open at the directory the user last selected, during the lifetime off your application.
OpenFileDialog OpenFile = new OpenFileDialog();
OpenFile.RestoreDirectory = false;
I find that all you have to do is NOT set the initial directory and the dialog box remembers your last save/open location. This remembers even after the application is closed and reopened. Try this code with the initial directory commented out. Many of the suggestions above will also work but if you are not looking for additional functionality this is all you have to do.
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
//openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
I know this is a bit of an old thread, but I was not able to find a solution I liked to this same question so I developed my own. I did this in WPF but it should work almost the same in Winforms.
Essentially, I use an app.config file to store my programs last path.
When my program starts I read the config file and save to a global variable. Below is a class and function I call when my program starts.
public static class Statics
{
public static string CurrentBrowsePath { get; set; }
public static void initialization()
{
ConfigurationManager.RefreshSection("appSettings");
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
CurrentBrowsePath = ConfigurationManager.AppSettings["lastfolder"];
}
}
Next I have a button that opens the file browse dialog and sets the InitialDirectory property to what was stored in the config file. Hope this helps any one googling.
private void browse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog open_files_dialog = new OpenFileDialog();
open_files_dialog.Multiselect = true;
open_files_dialog.Filter = "Image files|*.jpg;*.jpeg;*.png";
open_files_dialog.InitialDirectory = Statics.CurrentBrowsePath;
try
{
bool? dialog_result = open_files_dialog.ShowDialog();
if (dialog_result.HasValue && dialog_result.Value)
{
string[] Selected_Files = open_files_dialog.FileNames;
if (Selected_Files.Length > 0)
{
ConfigWriter.Update("lastfolder", System.IO.Path.GetDirectoryName(Selected_Files[0]));
}
// Place code here to do what you want to do with the selected files.
}
}
catch (Exception Ex)
{
MessageBox.Show("File Browse Error: " + Environment.NewLine + Convert.ToString(Ex));
}
}
You can use the InitialDirectory property : http://msdn.microsoft.com/fr-fr/library/system.windows.forms.filedialog.initialdirectory.aspx
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.InitialDirectory = previousPath;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
previousPath = Path.GetDirectoryName(openFileDialog1.FileName);
acc_path = openFileDialog1.FileName;
Settings.Default.acc_path = acc_path;
foreach (string s in File.ReadAllLines(openFileDialog1.FileName))
{
accs.Enqueue(s);
}
label2.Text = accs.Count.ToString();
}
if your using
Dim myFileDlog As New OpenFileDialog()
then you can use this to restore the last directory
myFileDlog.RestoreDirectory = True
and this to not
myFileDlog.RestoreDirectory = False
(in VB.NET)