Get complete file path from file click in File Explorer - c#

Using Visual Studio 2017 and Windows 10 I want to be able to open a file explorer and navigate to a file outside of the program. Once my file is collected I want to get the file path and the complete file name for the file explorer.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "All files (*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
textBoxFolderpath.Text= openFileDialog1.FileName;
if (textBoxFolderpath.Text.Contains('\\'))
textBoxFolderpath.Text = textBoxFolderpath.Text.Substring(0, textBoxFolderpath.Text.LastIndexOf('\\'));
This is what I have tried so far. The textBoxFolderpath is being used to hold the values.
What am I missing or doing incorrectly?

When working with filenames and paths I'd highly recommend using built-in classes to handle this, like the Path class:
Path.GetDirectoryName(openFileDialog1.FileName)
This returns the path, without the filename. It's also cross-platform compatible.

Thanks Zer0 - below is what I ended up using.
private void btnCurrentFolder_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog1 = new OpenFileDialog();
// Determine starting directory
if (chkSetToRoot.Checked)
{
openDialog1.InitialDirectory = #"K:\RESULTS";
}
openDialog1.Title = "Select A Test File";
openDialog1.Filter = "All Files (*.*)|*.*";
if (openDialog1.ShowDialog() == DialogResult.OK)
{
textBoxFolderpath.Text = Path.GetDirectoryName(openDialog1.FileName);
textBoxFileName.Text = Path.GetFileName(openDialog1.FileName);
}
}

Related

OpenFileDialog cannot read images

When I use OpenFileDialog to select a file on my WPF project I got an error window saying:
You do not have permissions to open this file.
Request permissions from the file owner or an administrator.
This only happen when I use image format files, with other type of file the File Dialog work as intended.
I already tried to open the app as admin and the error persists.
Test code:
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "jpg |*.jpg|png |*.png";
fileDialog.ShowDialog();
Perhaps you could try a new way which is safe at finding what file types you are looking for:
var dlg = new Microsoft.Win32.OpenFileDialog
{
Title = "Select an Image",
Filter = "Images |*.jpg; *.png",
CheckFileExists = true
};
if (dlg.ShowDialog() == true)
{
}
On file permissions try this https://windowsreport.com/no-permission-open-file/

C# winform File.Copy from a SaveDialog

I am attempting to copy a .txt from my application directory or some kind an export feature to users desire path and filename using savedialog on C# my code is below.
private void button2_Click(object sender, EventArgs e)
{
string directory = AppDomain.CurrentDomain.BaseDirectory + "output.txt";
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = "txt files (*.txt);
dialog.FilterIndex = 2;
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
}
}
}
But I am getting an error
The given path's format is not supported.
I am new with C# and want to understand this error and in addition, I want to set the file name extention default as .txt also, any suggestion would be great.
There are a couple of things you need to change.
First, of course, is your copy call. This line makes no sense
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
dialog.FileName contains already the full file name of your destination file. So there is no need to extract the directory and then add all the path again. Write just
File.Copy(directory, dialog.FileName);
But this creates a possible error. What if your user doesn't change the destination folder to another directory? You end up writing on the same file you want to read.
So I would add a sanity check like this
if(directory == dialog.FileName)
MessageBox.Show("Copy","Choose a different output folder");
else
File.Copy(directory, dialog.FileName);
Finally, if you want to force the output file to have always the .TXT extension you could add this line to the SaveDialog configuration
// Fix also your filter property. The one you have is invalid
dialog.Filter = "txt files (*.txt)|*.txt";
dialog.FilterIndex = 0; // 2 ?? There is no index 2 in your filter string
dialog.RestoreDirectory = true;
// Force the .TXT extension
dialog.AddExtension = true;

How to use openfiledialog to open any file as text in C#?

I am writing a winforms program in C# that uses the openfiledialog. I would like it to be able to take the file that the user selected and open it as text, regardless of the file type.
I tried it like this:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = Process.Start("notepad.exe", openFileDialog1.ToString()).ToString();
}
However, that didn't work and I'm not sure if I"m even on the right track.
You should use this code:
First add this namespace :
using System.IO;
Then add this codes to your function:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFileDialog.ShowDialog()== DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog.FileName);
}
To open the file using notepad, you need to pass the file name as second parameter of Start method. For example:
using (var ofd = new OpenFileDialog())
{
if(ofd.ShowDialog()== DialogResult.OK)
{
System.Diagnostics.Process.Start("notepad.exe", ofd.FileName);
}
}
Also if for any reason while knowing that not all file contents are text, you are going to read the file content yourself:
using (var ofd = new OpenFileDialog())
{
if(ofd.ShowDialog()== DialogResult.OK)
{
var txt = System.IO.File.ReadAllText(ofd.FileName);
}
}
What you are doing at the moment is starting a Process with the argument openFileDialog1.ToString(), calling ToString() on the process and setting this as text in the TextBox. If the path was valid, the result would probably be something like "System.Diagnostics.Process". But since you use openFileDialog1.ToString() as a path, your application probably crashes with a file not found error.
To get the selected file of an OpenFileDialog, use openFileDialog1.FileName. (See the docs here)
What I think you actually want to do, is read from the file and write its contents as text to the TextBox. To do this, you need a StreamReader, like so:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
using(var reader = new StreamReader(openFileDialog1.FileName))
{
textBox1.Text = reader.ReadToEnd();
}
}
This way, you open the file with the StreamReader, read its contents and then assign them to the text box.
The using statement is there because a StreamReader needs to be disposed of after you're done with it so that the file is no longer in use and all resources are released. The using statement does this for you automatically.

Save DIalogue that copies/loads another file

I am trying to save a file, but the actual file is already built and saved in a temp location, and I just want to move/copy that pre-built file to wherever the user chooses with the save dialogue.
What I have right now is this
fileName = the pathway of the file that is already built.
private void SaveFile()
{
SaveFileDialog savefile = new SaveFileDialog();
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(savefile.FileName))
sw.WriteLine(fileName);
}
}
Obviously right now this just writes the pathway to a text file, but I am trying to find a way to basically copy that file to wherever this user specifies.
you can do like
if (savefile.ShowDialog() == DialogResult.OK)
{
// you can use File.Copy
System.IO.File.Copy(fileName, saveFile.Filename);
}

Include resource file available for download

I am new to c# and I am almost done with a simple project. This project needs to include an excel file available for download using a LinkLabel
How can I include this file when compiling my project and when the LinkLabel is click it will as the user where to save the file.
My google search always point me to creating an excel, I dont need to create it, its already available, i just need to include in my resource file.
I am stuck here;
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
Now its working fine with the below code, I cant answer my question yet due to low score.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string filePath = null;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = saveFileDialog1.FileName;
File.WriteAllBytes(#filePath, Properties.Resources.importPurchases);
MessageBox.Show("File Successfully saved.\r\n\r\n" + filePath, "Success Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
return;
}
}
Add the excel file to your Project (Add -> Existing Item).
Right Click the added Excel File, go to Properties
Set Build Action to Content
Set Copy to Output Directory as Copy Always or Copy If Newer
By doing this; the Excel File would be copied to the output folder always after build.
var saveFileDialog = new SaveFileDialog();
saveFileDialog.DefaultExt = "xls";
saveFileDialog.Filter = "Excel files (*.xls)|*.xls |All files (*.*)|*.*";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
const string MyFileName = "myExcelFile.xls";
string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var filePath = Path.Combine(execPath, MyFileName);
Microsoft.Office.Interop.Excel.Application app = new Application();
Microsoft.Office.Interop.Excel.Workbook book = app.Workbooks.Open(filePath);
book.SaveAs(saveFileDialog.FileName); //Save
book.Close();
}
Update: The above sample is for Windows Application...

Categories