Load External Files with C# (From Resource Folder) - c#

I have a PDF file that I would like to load with a button click. I can reference the file in debug mode, but when I publish the project, the pdf doesn't migrate over or 'install' with the project.
The file is located in Resources/file.pdf
In the WPF form, I call the "OpenFile_Click" function on click.
Here is my function:
private void OpenFile_Click(object sender, RoutedEventArgs e)
{
string appPath = AppDomain.CurrentDomain.BaseDirectory;
Process.Start(appPath + "Resources/file.pdf");
}
This clearly doesn't work to open that file. I can add ../../ in front of the Resources folder and it will open in debug, but that isn't very helpful.
So, what is the best option for opening an external file like a PDF?

After setting Properties\Copy to Output Directory = Copy if Newer as suggested by Clemens, I would also recommend the use of System.IO.Path.Combine to ensure the correct path delimiter for the platform.
If there is still an error when invoking the Process.Start then try starting "explorer.exe" with the combined file name. I successfully tested the following, see if you can repro.
private void OpenFile_Click(object sender, RoutedEventArgs e)
{
var filePath = System.IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Resources",
"file.pdf"
);
Process.Start("explorer.exe", filePath);
}

Related

How to include an excel file in the build windows form application

I have an excell file that I need to access via a button in my application. When debugging, I simply have to copy the file to the debug/bin directory and it works with this code:
private void button10_Click(object sender, EventArgs e)
{
string filename = "estimation 1.xls";
System.Diagnostics.Process.Start(filename);
}
but after building the project, I get a file cannot be found message when pressing the button. I tried including the file by dragging it into the solution manager but it still gives me the error. How can I include this excel file in the build? Will I need to change the code to access it?
Try the following if your spreadsheet is in the same directory as your application.
private void button10_Click(object sender, EventArgs e)
{
string fileName = Path.Combine(Application.StartupPath, "estimation 1.xls");
System.Diagnostics.Process.Start(fileName);
}
You will also need to import the System.Windows.Forms namespace at the top of your file.
using System.Windows.Forms;
Add File to Resources Folder
Change the property "copy to output directory" of file to copy
call with the process.Start, example:
public void openFile () {
System.Diagnostics.Process.Start ( Path.Combine ( Application.StartupPath, "Resources", "estimation 1.xls" ));
}

OpenFileDialog only loads files from the root

I have an C# application to load some files into my database, but when I try to load the file the application only load from one location (C:), but I need to be able to load the files from any location.
I use this function to load the files
private void cmdArchivoTotal_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialogoArchivo = new OpenFileDialog();
dialogoArchivo.InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
dialogoArchivo.Filter = "CSV Files (*.csv)|*.csv";
if (dialogoArchivo.ShowDialog().Value)
txtArchivoTotal.Text =
System.IO.Path.GetFullPath("\\"+dialogoArchivo.SafeFileName);
}
At first I was thinking this was for run the application in debug mode, but even deployed the application only load the files from "C:\".
How can I load files from any disk and directory?
You're using OpenFileDialog.SafeFileName, which only returns the filename, not the path. By prepending \, you're constricted to reading files from the current disk's root.
Just use the FileName property, which contains the full path:
txtArchivoTotal.Text = dialogoArchivo.FileName

Reading a file added manually in project as resource in VisualStudio

In my soloution, for one of the projects I have to add a binary file and read its content in the form_load event.
As you can see in the picture I have added it to the appropriate project and have set the Build Action to Content and Copy to Output Directory as Copy Always.
Now can somone please tell me how how to access this file?
private void SetupForm_Load(object sender, EventArgs e)
{
//Find the path to file then
//READ THE FILE
}
Now you should find this file in your output directory after building your project. Given the right path to the file, you can access this file with any method you want.
Some methods can help you to get the path to the file:
Directory.GetCurrentDirectory();
Environment.CurrentDirectory
I'm not sure exactly what you're trying to do with the file, and that will determine your best approach here. As per the answer here you have a couple of options. To paraphrase:
Serialization
Binary Reader
I think the best method was this, so far:
So when I add the file to the project, it will be in the same folder as the exetubale file of project resides. So for getting the path (including the name of exetuable file I had to use Application.ExecutablePath and to remove the file name and have the pure path to the folder I had to use Path.GetDirectoryName() and finally add the filename I wanted to acces to this path, as you can see below:
var path = Path.GetDirectoryName(Application.ExecutablePath) + "\\YourFileName.bin";
The API you call to read the file depends upon the type of file. But the general pattern is like this.
private void SetupForm_Load(object sender, EventArgs e)
{
System.IO.Stream input = Application.GetResourceStream(new Uri #"/MyApp;component/content.bin", UriKind.Relative)).Stream;
BinaryReader binaryReader = new BinaryReader(input);
}
You can directly readbytes from the file attached as resource.My resource in this example is SampleWordnew document.
byte[] bob = ReadBytesfromResources.Properties.Resources.SampleWordnew ;

Cannot locate the wav file in the root folder of the project

I have code below. It works fine. But I would like to locate the "sound.wav" file the folder of the project. I mean ı don't want to put it in "D:\audio\background\sound.wav". I put the audio file the folder of the project but I couldn't do that . What changes should I do in System.Uri(#"D:\audio\background\sound.wav"))"
Thanks.
my simple program is this. I just want to play sound.wav file from home folder.
private void button1_Click(object sender, EventArgs e)
{
var background = new System.Windows.Media.MediaPlayer();
background.Open(new System.Uri(#"D:\sound.wav"));
background.Play();
}
You can use Environment.CurrentDirectory to get current working directory of your application. Then use Path.Combine to create path to audio folder inside working directory:
var path = Path.Combine(Environment.CurrentDirectory, "audio", "sound.wav");
If you want add your audio files in the resources properties->resources->addresource,after you done that just do this:
SoundPlayer sndplayr = new SoundPlayer(YourNameSpace.Properties.Resources.TDB_Groove_04_140_BPM__RC_);
sndplayr.Play();
//TDB_Groove_04_140_BPM__RC_ was a file i have and added to my project just as example
If you prefer to place files in startup folder then:
var background = new System.Windows.Media.MediaPlayer();
background.Open(new Uri(Application.StartupPath + #"\YourWavFile.wav"));
background.Play();
Assuming you have a directory called audio in your project you could access the file with a string like this:
"..\audio\sound.wav"
Or if your application is being run in a directory further down in your project you can use "~" to access the home directory

Locating a file directory to display pdf in c#

I am having a problem with displaying a pdf in my form wen a menu item is clicked
the directory im using cant be found
the file is in the project folder
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(#"\\ColsTechieApp\\TechnicianApplicationUserManual.pdf");
}
when i enter the full location
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(#"C:\Users\UV Chetty\Dropbox\Final\Complete\ColsTechieApp (Complete)\ColsTechieApp\Technician Application User Manual.pdf");
}
it works how do i make the path exclusive to the project folder
Try using Environment.CurrentDirectory as your current set and combin it with Path.Combine
Should work, becaus you are using full path
First, you're trying to escape backslashes but the # specifies that the string shouldn't be escaped. (Plus, you seem to be missing whitespaces)
Secondly, Environment.CurrentDirectory inserts the current path. Used with Path.Combine, you'll have your entire location.
If you're really lazy, you can skip the Path.Combine and directly concatenate strings. Process.Start() probably converts it to a Path automatically.

Categories