OpenFileDialog and UnauthorizedAccessException - c#

I'm developing a tool that processes an .fbx model and user input into a single file for use in a game. The code for when the user presses the "Import Model" button is as follows, and is similar for every button:
private void E_ImportModelButton_Click_1(object sender, EventArgs e)
{
E_model = null; // byte array where model is stored
E_SelectedFileLabel.Text = "No Model Selected"; // label on form
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "FBX Model (.fbx)|*.fbx";
ofd.Multiselect = false;
if (ofd.ShowDialog() == DialogResult.OK)
{
// adjusts variables for game file
string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);
E_SelectedFileLabel.Text = "File Selected: " + ofd.FileName;
}
}
The problem is, whenever I click OK, an UnauthorizedAccessException occurs. I have tried importing files from C:\Users\Owner\Downloads as well as C:\Users\Owner\Desktop and the C:\ drive itself, but it still occurs. What could I add to this code to gain access to these (and other) folders?

You are trying to read from directory via the method intended to read from a file:
string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);
Replace it with:
E_model = File.ReadAllBytes(ofd.FileName);

You can't ready the directory, you have to read a file:
string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);
Try adding the file name here

Related

C# OpenFileDialog importing variable

Still new to C#, snipping some code around to write a simple application and learning while doing.
I have an xml file that needs to be ingested and set as a variable so I can have it just insert words from that text file into different text fields.
private void button1_Click(object sender, EventArgs e)
{
// Displays an OpenFileDialog so the user can select a datafeed.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Datafeed File|*.dfx5";
openFileDialog1.Title = "Select a dfx5";
// Show the Dialog.
// If the user clicked OK in the dialog and
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Assign the file as a variable.
}
}
How would I make that file a variable so that I can read from it?
Thank you in advanced. Google-ing didn't return anything helpful
How would I make that file a variable so that I can read from it?
Well, the file name that was selected is a property of the OpenFileDialog object:
string fileName;
// Show the Dialog.
// If the user clicked OK in the dialog and
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Assign the file as a variable.
fileName = openFileDialog1.FileName;
}
What you do with that file name at that point is up to you.
If you want to store the Filename in a variable, the other answers are what you are looking for.
To me it sounds like you need to actually read the content of the file.
If that's what you want, the following snippet (provided by Microsoft) should do:
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
// Read the stream to a string, and write the string to the console.
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
This way line will contain the XML data you need. How you proceed from there is up to you.
If the file is pure XML, then I'd be inclined to do something like this:
using System.Xml.Linq;
private XDocument _xmlPayload;
private void button1_Click(object sender, EventArgs e)
{
// Displays an OpenFileDialog so the user can select a datafeed.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Datafeed File|*.dfx5";
openFileDialog1.Title = "Select a dfx5";
// Show the Dialog.
// If the user clicked OK in the dialog and
var dialogResult = openFileDialog1.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
//Get file path from dialog
var filePath = openFileDialog1.FileName;
//load xml
using(var stream = File.OpenRead(filePath))
{
_xmlPayload = XDocument.Load(stream);
}
}
}
Then it's up to you how you work with the XML.
openFileDialog1.FileName should have the returned filename from the dialog. if multiselect is enabled I think its openFileDialog1.FileNames

Saving files with name read from text box. C#

I have created some code that saves my work to a text file, I was just wondering is there some way so that when I click 'Save' I can read in the text from richTextBox1and set it as the default file name, still with the 'txt' default file extension.
e.g. When I click 'save' the folder dialog comes up and asks you to name your file, just as it would if you were using Word for example, I want that box to already have the text from my richTextBox1 in.
Thanks.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = "C:\\To-Do-List";
save.Filter = "Text Files (*.txt)|*.txt";
save.DefaultExt = ".txt";
DialogResult result = save.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamWriter SW = new StreamWriter(save.FileName))
{
SW.WriteLine(richTextBox1.Text);
SW.WriteLine(richTextBox2.Text);
SW.WriteLine(richTextBox3.Text);
SW.WriteLine(richTextBox4.Text);
SW.WriteLine(richTextBox5.Text);
SW.Close();
}
}
Just set the FileName property on your SaveFileDialog.
Add
save.FileName = String.Format("{0}.txt", richTextBox1.Text);
Before you call ShowDialog.

Executing another Application with selected file using a button (C# Programming)

To start, I'm a newbie with C# Programming and I've tried googling for solutions about my problem but it seems that i cannot find one, or simply too unlucky or too blind to spot one. I'm using Microsoft Visual Studio 2005.
Anyways. I was assigned to modify/create an automated test environment input application. The said application already has a function to run/start a CANoe program with a pre-defined file or if it's already running, stop the program.
private void button1_Click(object sender, EventArgs e)
{
// Execute CANoe(Obtain CANoe application objectg)
mApp = new CANoe.Application();
mMsr = (CANoe.Measurement)mApp.Measurement;
try
{
mApp.Open("C:\\Users\\uidr3024\\Downloads\\SRLCam4T0_Validation_ControlTool\\cfg\\SVT_SRLCam4T0_025B.cfg", true, true);
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
// Finish CANoe
if (mApp != null) {
mApp.Quit();
}
// Release the object
fnReleaseComObject(mMsr);
fnReleaseComObject(mApp);
}
What I wanted to do now is to have an OpenFileDialog box that will show a selection of files and user will be able to browse and select any file to start the CANoe program with the selected file and not just the file path that's been input in the code along the "mApp.Open()" syntax. I've tried this:
private void button5_Click_1(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\Users\uidr3024\Downloads\SRLCam4T0_Validation_ControlTool\cfg";
openFileDialog1.Title = "Browse Configuration Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.Filter = "CANalyzer/CANoe Configuration (*.cfg)|*.cfg |All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
}
I've tried this code that I often see in the Web and in the Tutorials but I don't know how to incorporate it with the button for running the CANoe program so that when user clicks the Open button from the Dialog Box, the file path would be shown in the textbox(optional) and/or when the user then clicks the Start CANoe, CANoe program would start with the selected .cfg file.
Am I making any sense here? Or am I doing the right thing here?
Btw, I found these... And I'm using a CANoe library for these, ofc.
#region "***** CANoe Object definition *****"
private CANoe.Application mApp = null; // CANoe Application CANoeƒAƒvƒŠƒP[ƒVƒ‡ƒ“
private CANoe.Measurement mMsr = null; // CANoe Mesurement function CANoe‘ª’è‹#”\
private CANoe.Variable mSysVar = null; // System variable ƒVƒXƒeƒ€•Ï”
private CANoe.Variable mSysVar_start = null; // System variable ƒVƒXƒeƒ€•Ï”
#endregion
I think you have done most of the hard work, unless I've missed something I think you just need something like this in your button1_Click method:
if( textBox1.Text != String.Empty && System.IO.File.Exists(textBox1.Text) )
{
// The textbox has a filename in it, use it
mApp.Open(textBox1.Text, true, true);
}
else
{
// The user hasn't selected a config file, launch with default
mApp.Open("C:\\Users\\uidr3024\\Downloads\\SRLCam4T0_Validation_ControlTool\\cfg\\SVT_SRLCam4T0_025B.cfg", true, true);
}

Get File Name from a Path in Listbox Item

I want to reduce the length of the path and display only the file name.
For example, suppose the path is c:\\program files\...\123.jpg I want to display only 123.jpg.
Here is the code I have been working with thus far. Can anyone suggest modifications?
private void button1_Click(object sender, EventArgs e)
{
panel3.Controls.Clear();
var ofd = new OpenFileDialog();
ofd.Multiselect = true;
ofd.Filter = "DICOM Files (*.dcm;*.dic)|*.dcm;*.dic|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.Cancel)
return;
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(s);
}
}
There is a class named Path in System.IO namespace.
Between its numerous static methods you could find
Path.GetFilename(string);
Using it in your Add loop you could set only the filenames
listBox1.Items.Add(Path.GetFileName(s));
However, I suggest to save the folder name somewhere, because if you need to process these files you need it. And, guess what, Path has a method also to extract a path from a full filename
if(filenames.Length > 0)
string workingPath = Path.GetDirectoryName(filenames[0]);
EDIT
From your comments below it seems that you call this button_click more than one time and every time you select a different folder. In this case, stripping the path part from the selected filenames leaves your listbox filled with files that you can't retrieve because you don't know the path part (stripped away). If you need to retrieve the files selected to execute some kind of process, then you need to store somewhere the full path of these files and be able to retrive them.
You can achieve this result storing the files selected in a List<string> instance.
Declare at the global level a variable to store these full filenames
(Add using System.Collection.Generic;)
List<string> selectedFiles = new List<string>();
Now inside the button click add the full filename to the List<string> and the stripped file to the ListBox items, in the same order
private void button1_Click(object sender, EventArgs e)
{
panel3.Controls.Clear();
var ofd = new OpenFileDialog();
ofd.Multiselect = true;
ofd.Filter = "DICOM Files (*.dcm;*.dic)|*.dcm;*.dic|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.Cancel)
return;
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(Path.GetFileName(s));
selectedFiles.Add(s);
}
}
Now, if you want to retrieve the full path for the selected file in the listbox you could use
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(listBox1.SelectedIndex >= 0)
{
string fullFileName = selectedFiles[listBox1.SelectedIndex];
.... process the filename ....
}
}
Use Path.GetFileName() to return the name
see http://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx

C# After using OpenFileDialog, a MessageBox doesn't open on top

Our primary database application has a feature that exports either an Excel workbook or an Access mdb for specified work orders. Those files are then sent to our subcontractors to populate with the required data. I am building an application that connects to the files and displays the data for review prior to being imported into the primary database. Simple enough, right? Here’s my problem: the application opens a OpenFileDialog box for the user to select the file that will be the datasource for the session. That works perfectly. If I open a MessageBox after it, that box open up behind any other open windows. After that, they respond correctly. I only expect to be using MessageBoxes for error handling, but the problem is perplexing. Has anyone encountered this problem?
The MessageBoxes in the code are only to verify that the path is correct and to solve this problem; but, here’s my code:
private void SubContractedData_Load(object sender, EventArgs e)
{
string FilePath;
string ext;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Microsoft Access Databases |*.mdb|Excel Workbooks|*.xls";
ofd.Title = "Select the data source";
ofd.InitialDirectory = ElementConfig.TransferOutPath();
if (ofd.ShowDialog() == DialogResult.OK)
{
FilePath = ofd.FileName.ToString();
ext = FilePath.Substring((FilePath.Length - 3));
if (ext == "xls")
{
MessageBox.Show(FilePath);
AccessImport(FilePath);
}
else if (ext == "mdb")
{
MessageBox.Show(FilePath);
AccessImport(FilePath);
}
}
else
{
System.Windows.Forms.Application.Exit();
}
}
While it isn't advisable to use MessageBoxes to debug your code, I think the immediate problem is that you are doing this in the form's load event.
Try it like this:
protected override void OnShown(EventArgs e) {
base.OnShown(e);
// your code
}
Your problem is definitely the fact that you're trying to do this while loading the Form, because the form isn't yet displayed.
Another alternative would be moving this functionality out of the Load event and give the user a button to push or something like that.
In other words:
private void SubContractedData_Load(object sender, EventArgs e)
{
// unless you're doing something else, you could remove this method
}
Add a button that handles this functionality:
private void SelectDataSourceClick(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Microsoft Access Databases |*.*|Excel Workbooks|*.xls";
ofd.Title = "Select the data source";
ofd.InitialDirectory = ElementConfig.TransferOutPath();
if (ofd.ShowDialog() == DialogResult.OK)
{
var FilePath = ofd.FileName.ToString();
var ext = Path.GetExtension(FilePath).ToLower();
switch (ext)
{
case ".xls":
MessageBox.Show(FilePath);
AccessImport(FilePath);
break;
case ".mdb":
MessageBox.Show(FilePath);
AccessImport(FilePath);
break;
default:
MessageBox.Show("Extension not recognized " + ext);
break;
}
}
else
{
System.Windows.Forms.Application.Exit();
}
}

Categories