c# Get Path from a busy file using openFileDialog in winforms - c#

I'm trying go get a path to a 'busy' file using openfiledialog in winforms and C#. Using the following code:
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
this.dbPath = this.textBox1.Text;
}
}
When I point to the file in question I get the following error:
Error Message:
MyDbContext.mdf
This file is in use.
Enter a new name or close the file that's open in another program.
Which is fine, because I already know the file is in use, all I want is to store the file path into a string, without opening it.
Perhaps openfiledalog is the wrong option here, after all I don't want to open the file, only to list it's path. However I didn't find anything else in winforms that points to a file.
Is there any other means to achieve what I want?

Try setting ValidateNames to false before ShowDialog()
openFileDialog1.ValidateNames = false;

Related

C# WPF Have User select file then use the functions within that file

I'm new to using C# and WPF so I apologize if my terminology is incorrect.
I want trying to make a program to automate small businesses workflows, the base application is the same for everyone, but how their order data is structured is going to be different.
So, my goal would be to build them a custom file that contains function on how to parse their order data, then have the user drag and drop that file into the application to which the application would use it.
I have a way for them to select the file and move it into the applications directory here:
private void SelectFile_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".cs";
dlg.Filter = "C# Files (*.cs)|*.cs";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filePath = dlg.FileName;
string relPath = AppDomain.CurrentDomain.BaseDirectory;
string destPath = System.IO.Path.Combine(relPath, dlg.SafeFileName);
Trace.WriteLine(destPath);
File.Move(filePath, destPath, true);
}
}
But now I run into an issue when I want to call from that file I get a error "CS0103" the file doesn't exist in the current context. So I am now unable to run the application
Is there a way around this error? so it will only run when the file exists and get rid of this error?
I have tried to check if the file exists before calling it, but the same error prevents me from running my app.
//call your order parser script
if (File.Exists("OrderParser.cs"))
{
OrderParser.OrderParser.Parser(item);
}

Why my OpenFileDialog didnĀ“t work?

I try to open a textdocument and then I get the message: invalid file format from the try-catch. I use Visual Studio 2015 with Visual C# and Windows Forms Application.
Here my code for the open function:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
try {
// Create an OpenFileDialog to request a file to open.
OpenFileDialog openFile1 = new OpenFileDialog();
// Initialize the OpenFileDialog to look for RTF files.
openFile1.Filter = "Text Files (*.txt)|*.txt| RTF Files (*.rtf)|*.rtf| All (*.*)|*.*";
// Determine whether the user selected a file from the OpenFileDialog.
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
openFile1.FileName.Length > 0)
{
// Load the contents of the file into the RichTextBox.
TextBox.LoadFile(openFile1.FileName);
}
}
catch (Exception a)
{
MessageBox.Show(a.Message);
}
}//end open
I hope you can help me with friendly wishes sniffi.
The problem is probably that you don't load a RTF document - see the docs on MSDN.
With this version of the LoadFile method, if the file being loaded is
not an RTF document, an exception will occur. To load a different type
of file such as an ASCII text file, use the other versions of this
method that accept a value from the RichTextBoxStreamType enumeration
as a parameter.
So try to use the overloaded version of this method which accepts the stream type like so (adjust to your needs)
TextBox.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);

How to give user an options to save file in there desired location in C#?

I know how to create and save a file in C# console application but what if i want the user to choose the location of where they want to save it? i have no idea on how i can make this possible.
edit- ive realised that would be very hard to input the location the user wants to save the file to however is it possible to save the file as you would do when creating a windows word document, so the user would be able to see where they want to save the file Example
If you want a full console application, that is no windows being created, then there's only one proper thing to do: require the user to specify the save location on the command line.*
Given the fact that you have a console application, you probably already do some checking of the command line, but if not, then the command line can be read from the args argument to your Program.Main:
static void Main(string[] args)
{
...
}
There are examples on the internet to handle the command line, if you get stuck, or a new question can be asked specifically for the issue you are having.
*) Now, for the reason why this is the only proper way:
If the user needs to pass it on the command line, then the user has all the usual niceties such as tab completion available. The user can also use dir and cd before calling your program to find the proper directory.
On the other hand, if you ask the user to input it, then the user will not have tab completion, will not be able to use dir or cd, and as such will have to type it out manually all the way. Typo's or mistakes are almost guaranteed.
From a user experience point of view, this is very annoying. Programmers should therefore not ask the user to manually type out file paths during program execution. Hence, it must be specified on the command line.
Read about SaveFileDialog
private void button1_Click(object sender, System.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)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
And ready to test example from msdn example
if you want to play with something like >cd (ChDir) then look at
Environment.CurrentDirectory
or/and force user to write good directory by himselft and use #Carl aswere :) but remember we leave in 21 century people are lazy
You can use the SaveFileDialog as Taumantis said but you have to add the
System.Windows.Froms
namespace and you must mark your main method as a single apartment thread
class Program
{
[STAThread]
static void Main(string[] args)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
}
Console.ReadKey();
}
It is not hard. You need a console to read user's input with string path = Console.ReadLine();. User will input prefered path and it will store into path variable. Now you should check if this path exits if(Directory.Exists(path)) it will return true if path exists false if path does not exist.
Code example:
Console.WriteLine("Insert a path: ");
string path = Console.ReadLine();
if(Directory.Exists(path)){
//save logic
}
else{
//path does not exist handler
}
Note: if you want to access Directory class you should use System.IO namespace.

Get full file path including file's name from an uploaded file in C#

I have this web application project which requires a better user-interface and I am doing it by C#.
I already have my html file with JS done but I need some data from user.
In my JS embedded in HTML file, I used the code below to find the file on local driver and get the data from that excel file and then put all these data into an array.
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open(file1);
var excel_sheet = excel.Worksheets("Sheet1");
However, the "file1" you see above seems to require a full name path,say "C:\test.xls" in my case.
I am new to C# and just built a button on my form design, by clicking the button, I seem to be able to browse my local file.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
System.Diagnostics.Process.Start(file);
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
So, my question:
How can I get this kind of full file path of an uploaded file in C# ?
And furthermore, it would be awesome if some one can tell me how to get this value into my javascript or HTML!
Thank you in advance
You won't be able to depend on getting the full path. In the end, the browser only needs to multi-part encode the physical file and submit it as a form post (of sorts). So once it has it's location and has encoded it -- it's done using it.
It's considered a security risk to expose the file structure to Javascript/HTML (ie., the internet).
Just an update.
I used another logic and it worked as expected. Instead of getting absolute file path , I managed to open the file , save it as somewhere and make my html call find that file path no matter what.

trouble saving bitmap to file in C#

I'm trying to save a bitmap to a file, all the examples and tutorials I have found suggest using this line of code to do so-
private void saveImageToolStripMenuItem_Click(object sender, EventArgs e) // Save the fractal image
{
SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
fractal.Save("myfile.png", ImageFormat.Png);
}
}
When I execute the code by click the save image button (which calls the above method) a save dialog appears but both the file name field and file type field are empty. I select a location to save to and give the file a name - e.g. bitmap.png then check the location and nothing has saved.
I have also checked the debug folder and nothing has appeared there ether.
I'm assuming I'm not far off or that I've made a silly mistake elsewhere any ideas or suggestions?
Assuming you are using the SaveFileDialog class, you need to set the Filter and DefaultExt properties to get the file extensions to show up.
You then read the FileName property as the argument to your Save() call

Categories