C# - Access negated to path - openFileDialog - c#

I'm new to developing, I make a simply app to try to open a file the app return me an error: "access to the path negated" but I'm administrator, UAC is disabled and I'm the only account, why did it give me this error?
Here my code:
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;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
string sourceCode = File.ReadAllText(Path.GetDirectoryName(openFileDialog1.FileName));
string colorizedSourceCode = new CodeColorizer().Colorize(sourceCode, Languages.Java);
textBox1.Text = colorizedSourceCode;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}

Looks to me like you're trying to open a stream on a folder.
Try replacing this
string sourceCode = File.ReadAllText(Path.GetDirectoryName(openFileDialog1.FileName))
with this:
string sourceCode = File.ReadAllText(openFileDialog1.FileName)

Your opening the stream wrong.
Maybe try something like this?
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;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string strfilename = openFileDialog1.FileName;
string filetext = File.ReadAllText(strfilename);
textBox1.Text = filetext;
button1.PerformClick();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}

Related

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...
}

Why when using openFileDialog i don't see all the settings i changed?

In top of form1 i did
OpenFiledialog openFileDialog1 = new OpenFiledialog();
Then:
private void changeWorkingDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
openFileDialog1.Filter =
"BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
if (result == DialogResult.OK)
{
string[] files = openFileDialog1.FileNames;
try
{
if (files.Length > 0)
{
label6.Text = files.Length.ToString();
label6.Visible = true;
string directoryPath = Path.GetDirectoryName(files[0]);
label12.Text = directoryPath;
label12.Visible = true;
}
}
catch (IOException)
{
}
}
}
But when i click the button the init directory is documents and not c: and i don't see the filter/s at all but i see all the files. It's like the settings i did didn't effect.
ShowDialog is modal, so it waits until the user clicks OK/Cancel.
Only then does the rest of your code run.
You should only call ShowDialog after you have finished setting the properties:
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg...";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
Your logic is incorrect. You're displaying the dialog before you configure the settings.
// Configure it first
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
// Then show it and wait for the user to make a selection or cancel
DialogResult result = openFileDialog1.ShowDialog();
// Take some action if the user made a selection
if (result == DialogResult.OK)
{
...
As a side note, be careful about eating exceptions. At the least, log the error and inform the user.
catch (IOException ex)
{
// log ex.ToString() somewhere
MessageBox.Show("An error has occurred!\r\n\r\n" + ex.Message);
}
The problem is you are calling ShowDialog() before settings the properties, this should work for you:
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string[] files = openFileDialog1.FileNames;
try
{
if (files.Length > 0)
{
label6.Text = files.Length.ToString();
label6.Visible = true;
string directoryPath = Path.GetDirectoryName(files[0]);
label12.Text = directoryPath;
label12.Visible = true;
}
}
catch (IOException)
{
}
}

system.notsupportedexception the given path's format is not supported

In my chat program I need to send file to other users but I have problem.
When I trying to send my file visual studio give me an exception the given path's format is not supported;
private void button3_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "A:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer).ToString();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
byte[] bytes = File.ReadAllBytes(openFileDialog1.ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error:"+ ex.Message);
}
}
}
Please help.
Try File.ReadAllBytes(openFileDialog1.FileName);.
You're using openFileDialog1.ToString(), which will return something like "System.Windows.Forms.OpenFileDialog", not the path of the selected file.

display file instead of RSC version

Whenever I try to open a custom file to a textbox or something which will display code. it never works, I'm not sure what I am doing wrong.
I want my program to display what is inside the file when I open it, I have this below:
private void button1_Click(object sender, EventArgs e)
{
//Show Dialogue and get result
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "rbt files (*.rbt)|*.rbt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show("RBT7 file open");
}
}
}
It only displays the RBT7 in a messagebox which is not what I want, I want the file to open and display its information to some sort of textbox which displays code.
Please read the documentation for File.WriteAllText.
The first parameter:
path: The file to write to.
You're passing it "". That is not a path. Are you trying to write all the text from the file into CodeBox.Text or write all the text from CodeBox.Text into a file?
In your comment, you indicate the former. Try this:
string[] lines = System.IO.File.ReadAllLines(#"your file path");
foreach (string line in lines)
{
CodeBox.Text += line;
}
You haven't shown the code for CodeBox so I can't guarantee the results of this.
Try this:
Replace this code
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
with this
{
CodeBox.Text = File.ReadAllText(openFileDialog1.FileName);
}

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