How to open the file if path is known? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am having path in listbox.I want to open the file on listbox item click.
I am using SelectedIndexChanged,From that I am able to know item which is clicked. Now, I want to open that.

public void OpenDialogBox()
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "*YOURTEXTBOX.text";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
//Do something with Open File
}
}
catch (Exception ex)
{
// You messed up
}
}
}

Related

How to store data in datagrid using regex and remove dublicates C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
I need some help please. I need to remove dublicates and use regex when load a list of email adresses in datagrid. Regex must check for syntax email adress to be correct.
Here is my code:
public void StoreEmailToDataGrid(string filePath, DataGridView dataGridView)
{
try
{
var baca = File.ReadLines(filePath);
foreach (var line in baca)
{
var rowIndex = dataGridView.Rows.Add();
dataGridView.Rows[rowIndex].Cells[0].Value = rowIndex + 1;
dataGridView.Rows[rowIndex].Cells[1].Value = line;
}
this.totalRows = dataGridView.Rows.Count;
}
catch (IOException)
{
}
}
private void buttonImportMailist_Click(object sender, EventArgs e)
{
string file = "";
openFileDialog1.Filter = "Text Files|*.txt";
openFileDialog1.Title = "Select Mailist";
openFileDialog1.FileName = file;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
file = openFileDialog1.FileName;
try
{
email.StoreEmailToDataGrid(file, dataMailist);
}
catch (IOException)
{
MessageBox.Show(result.ToString());
}
}
}
UPD: Remove dublicates solved
var baca = File.ReadLines(filePath).Distinct().ToArray()
Remain, how to use regex to check correct email adresses.
Solved the problem. Just use regex.ismatch
Regex.IsMatch(strIn, #"^([\w-.]+)#(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([\w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$");

openfiledialog results in file is being used by another process [duplicate]

This question already has an answer here:
System.IO.IOException: 'The process cannot access the file because it is being used by another process
(1 answer)
Closed 2 years ago.
I would like use C# to upload multiple files to google drive
this is my upload button function
private void bt_upload_Click(object sender, EventArgs e)
{
Filedialog_init();
DialogResult check_upload = MessageBox.Show("Want to upload these files ?", "Upload", MessageBoxButtons.OKCancel);
if (check_upload == DialogResult.OK)
{
for (int i = 0; i < result.Count; i++)
{
UploadFilesDrive(service, result[i], filePath[i], Datatype[i]);
tx_state.AppendText(result[i] + "Upload Done");
}
}
}
This is my Filedialog_init function
private static void Filedialog_init()
{
Stream myStream = null;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filename = null;
string _datatype = null;
try
{
if ((myStream = openFileDialog.OpenFile()) != null)
{
foreach (String file in openFileDialog.FileNames)
{
filename = Path.GetFileName(file);
result.Add(filename);
// only show the name of file
Datatype.Add(_datatype);
}
filePath = openFileDialog.FileNames;
Datatype.ForEach(Console.WriteLine);
}
openFileDialog.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
else
MessageBox.Show("Upload Cancel");
}
I can upload the file successfully by assigning the filename and its datatype and path directly
But when I used openfiledialog,it went wrong with "my file is being used by another process"
How can I solve this problem?
Issue lies in your code here,
(myStream = openFileDialog.OpenFile()) This line is keeping lock on the file because your myStream does not get disposed. you need to dispose the stream as soon as you are done with it.
So try with using as it will dispose the stream as soon as your end using line gets executed. More details on using.
you can try as below,
using(Stream myStream = openFileDialog.OpenFile())
{
//Your code here...
}

How to Save contents of a textbox to a file

I have looked around on several answers to similar questions, but somehow this isnt working for me.
I am trying to save the contents of a textbox into a user promptet file.
private void btnSave_Click(object sender, EventArgs e)
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
File.WriteAllText(saveFileDialog1.FileName, rtbIncoming.Text);
myStream.Close();
}
}
}
The User prompt pops up as expected, and the file is generated but without any content.
You don't need to open the file stream yourself. File.WriteAllText() does all this for you. So this should be enough:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
File.WriteAllText(saveFileDialog1.FileName, rtbIncoming.Text);
I guess your code leads to an empty file because you open a seperate stream that isn't used to write and closed (and flushed) after the call to WriteAllText().

How to open a file in C# using FileOpenDialog

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
}

How to save last folder in openFileDialog?

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)

Categories

Resources