Path is wrong (FileNotFoundException) - c#

I have this chunk of code:
private void button4_MouseEnter(object sender, MouseEventArgs e)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"Resources/navigation.wav");
player.Play();
}
And I get FileNotFoundException, but navigation.wav is in Project/Resources. Plese help!!!

This looks for the file from your Bin\Debug Folder
You have couple of options:
Right click the file and pick Properties. Select for BuildAction = Content.
You will find the file under Bin\Debug\Resource\Sound.wav
Right click the file and pick Properties. Select for BuildAction = Embedded Resource.
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "NamespaceName.FolderName.Sound.wav";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
var wave = new WaveFileReader(stream);
Console.WriteLine(wave.TotalTime);
}

The path is determined relatively from the executable, so in this case probably Bin\Debug.
Try to add the resource in your application as Content (it copies the file to Bin\Debug). That should work.

That path is relative to the directory in which the application is currently running. If you hit F5 in Visual Studio this is most probably bin/Debug, so the file should be there.
Consider embedding this resource, or setting Copy to output directory property to "copy always".

To start with, you need a backslash: #"Resources\navigation.wav"
If this doesn't help, then most likely you are running your application from a different directory than you think. Are you running in debug mode from VS? Is your file in Project\bin\Debug\Resources then?

Related

C#: opening a text file stored within the same project as the app

I managed to open a text file using an absolute path (in Visual Studio 2017) although if I change the location of my Solution folder the whole code would not work anymore as the actual physical path has changed and the code can not reference an existing location anymore.
I tried to create a text file within the same project and I would now like to open this file in my code, so if the location of the whole Solution changes the program can still work, would anyone be so kind to help me fix this issue?
I have also looked online for some different solution using code that references the current directory but I can't get my head around it as the current directory seems to be bin/debug and if I try to insert the file there the code doesn't recognize the location (also it doesn't look like a clean solution to me).
This is the code I am using so far in a WPF app, the whole purpose is to open the content of the text file containing countries listed line by line and to add them to a list box which will be displayed when a checkbox will be ticked.
private void listCountry_Initialized(object sender, EventArgs e)
{
listCountry.Visibility = Visibility.Hidden;
string path = "C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\StudentRecord\\country.txt";
if (File.Exists(path))
{
string[] myCountryFile = File.ReadAllLines(path);
foreach (var v in myCountryFile)
{
listCountry.Items.Add(v);
}
}
}
This is a great use case for OpenFileDialog Class.
Represents a common dialog box that allows a user to specify a filename for one or more files to open.
Here is the example of use, from the documentation.
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
Assuming C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\ is your project, and StudentRecord\\country.txt is a project folder and file in your project - you need change "Copy to Output Directory" to be "Always Copy" or "Copy If Newer" and "Build Action" to "Content" for the file in your project.
As you can see from the screenshot above, the folder structure for this content is created as well.
Then change your path assignment to be something like the following:
string path = string.Join(#"\", Application.ExecutablePath, #"StudentRecord\country.txt");
Clean and simple, place the file you want to open next to where the executable is generated, remember the executable path changes depending to if your project is in Debug or Release build mode. Now set:
string path = "country.txt";
By only providing a filename, the file is looked for in the same folder as the executable. Just remember that when you move the executable you must also move the file to the same place, but if you move the entire project folder then you're already set.
However, if you want to keep your file in a fixed location regardless of where you have your executable and/or VS project files, then the simplest path for it is:
string path = "C:\\country.txt";
This is an absolute path, but it's quite simple and very robust to changes, you would have to change the drive letter to break it and if C: is where your operating system files are then you probably won't do that.
If you don't like to have your files around in your root, you can always have a path like this:
string path = "C:\\ProjectNameFiles\\country.txt";
Or if you prefer to maintain a hierarchy of projects then you can use:
string path = "C:\\MyProjectsFiles\\ProjectName\\country.txt";
With this, every project can have a directory for the files it needs to open. These are all absolute paths, but are notably simpler than the one you posted, and they have a more fixed and organized structure.

Referencing a file inside of a Project without using its absolute path?

I'm using StreamReader to dynamically replace content in an HTML template. The HTML file has been imported into my project.
Right now I'm having to referencing the HTML file a static location on my dev box because I'm not able to find the right syntax to reference it once it's been imported into my VS project.
How do I refer to the file without using an absolute path?
Current implementation for reference:
StreamReader reader = new StreamReader(#"C:\Users\n00b\Desktop\EmailTemplate.html");
{
body = reader.ReadToEnd();
}
One common thing I've seen is to put the file's location in a configuration file. This lets you change the file location at will without having to recompile.
You can add it as an embedded resource and extract it this way.
using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("<namespace>.Resources.EmailTemplate.html"))
per your comment
using (System.IO.StreamReader sr = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("<namespace>.Resources.EmailTemplate.html"))
{
body = sr.ReadToEnd();
}
There are 2 main ways to do this, In a desktop application, the current directory of the .exe is set to the directory where it is launched from by default. Unless that is changed by launching the .exe by a shortcut with special settings, or by another process using a special feature, it should be the default value. If that is the case, you can just use a relative path. For example, if you have a file named "data.txt" in a folder called "things" inside a folder called "stuff" in the same directory as your app, you can just us the relative path "stuff/things/data.txt" directly and Windows will work it out for you.
If you need to be absolutely sure you are targeting that file, even if the app launches with a modified current directory, you can get the .exe's path, and combine it with a relative path using System.IO.Path.Combine.
var appPath = Assembly.GetEntryAssembly().Location;
var filePath = "stuff/things/data.txt"
var fullPath = System.IO.Path.Combine(appPath, filePath)
If, for some reason, you need to up "up" from the application's directory, you can use ".." to represent that parent folder of a directory. So "../data.txt" would look in the folder that contains the current directory for a file named "data.txt".
You could also change the app's current directory when it starts to be the directory of the .exe, and then reference everything via relative path, as in the first example.
var appPath = Assembly.GetEntryAssembly().Location;
System.IO.Directory.SetCurrentDirectory(appPath);
I found two solutions to this:
If you don't care if the external file is visible in the build directory/installdir of your app:
StreamReader reader = new StreamReader(#"../../EmailTemplate.html");
{
body = reader.ReadToEnd();
}
If you want your external file to be invisible once compiled:
var embeddedResource = "<namespace>.EmailTemplate.html";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResource))
{
StreamReader sr = new StreamReader(stream);
body = sr.ReadToEnd();
}
Note the 2nd solution requires adding your external file and changing the build action to "Embedded Resource" on the properties menu of that file within Visual Studio.

How to display chm file in c# winforms application

I have added .chm file to my application root. when i fetch the file using below code it is referencing the path to bin/release/somehting.chm
System.Windows.Forms.Help.ShowHelp(this, Application.StartupPath+"\\"+"somehting.chm");
i want to get the path relative to installation location of application. please help.
the chm file added to the root directory is not loading after deploying the application. its not even loading while debugging in visual studio and not giving any error.
As I can see the first code snippet from your question calling Help.ShowHelp isn't so bad. Sometimes I'm using the related code below. Many solutions are possible ...
Please note, typos e.g. somehting.chm are disturbing in code snippets.
private const string sHTMLHelpFileName = "CHM-example.chm";
...
private void button1_Click(object sender, EventArgs e) {
System.Windows.Forms.Help.ShowHelp(this, Application.StartupPath + #"\" + sHTMLHelpFileName);
}
So, please open Visual Studio - Solution Explorer and check the properties of your CHM file. Go to the dropdown box shown in the snapshot below and set "Always copy" (here only German). Start your project in Debug mode and check your bin/debug output folder. Do the same for Release mode and output folder. The CHM should reside there and I hope your CHM call works.
You need :
String exeDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
So :
String HelpFilepath = "file://" + Path.Combine(exeDirectory , "somehting.chm");
Help.ShowHelp(this, path);
Answer from similar topic is:
// get full path to your startup EXE
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
// get directory of your EXE file
string exeDir = Path.GetDirectoryName(exeFile);
// and open Help
System.Windows.Forms.Help.ShowHelp(this, exeDir+"\\"+"somehting.chm");

Playing wav file which has relative path inside project

I have some problems with relative paths and reproduction of wav files. I have this simple code which works perfectly:
SoundPlayer player = new SoundPlayer();
player.SoundLocation = #"C:\Users\Admin\Documents\Visual Studio 2012\Projects\TestProject\TestProject\Data\Sounds\car.wav";
player.Play();
I want somehow to play that file with relative path but I didn't have success with this:
SoundPlayer player = new SoundPlayer();
player.SoundLocation = #"Data\Sounds\car.wav";
player.Play();
Thank you!
Is Data directory in the root directory of your application? Are you copying the directory contents as output?
If so, did you mean, Data\Sounds\car.wav?
Which, if running from Visual Studio would be in [projectroot]\[release]\bin\Data\Sounds\car.wav
If you don't see this directory in your bin folder, you'll need to ensure you're selecting all of the files you want copied to your output directory (which will copy the directory structure). You can do this by clicking on the file in your project and selecting the file as output.
Get the full path of your file with Path.GetFullPath("relativ/path")
You might be better off using absolute path after all. You can get the root path from the exe file, then append your relative path to it.
Like this:
// getting root path
string rootLocation = typeof(Program).Assembly.Location;
// appending sound location
string fullPathToSound = Path.Combine(rootLocation, #"Data\Sounds\car.wav");
player.SoundLocation = fullPathToSound;
//WindowsFormsApplication4.exe is name of name space this file name found in Debug file
//you should copy your "sound.wav" into your Debug file
string x = (Assembly.GetEntryAssembly().Location + "");
x = x.Replace("WindowsFormsApplication4.exe", "sound.wav");
SoundPlayer player1 = new SoundPlayer(x);
player1.Play();
This is worked for me
System.Media.SoundPlayer player1 = new System.Media.SoundPlayer(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\1.wav");

Accessing files from the project folder of a WP app

I'm new to Windows Phone development and I'm trying to do a simple training app.
I want my app to load some audio files that I've put into a folder inside the project.
Here's a short snippet:
private void LoadSound(String SoundFilePath, out SoundEffect Sound)
{
// For error checking, assume we'll fail to load the file.
Sound = null;
try
{
// Holds informations about a file stream.
StreamResourceInfo SoundFileInfo = Application.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));
My folder structure is something like
- Project
- Kits
- TestKit_128
- Bass_126.wav
and calling
Button.setSound("Kits\\TestKit_128\\bass_126.wav");
throws a System.NullReferenceException because the path is not found when the URI is created. (At least I think so!)
What should I do?
Is there any way to load files from a folder in the project or to copy them into the IsolatedStorage when I run the app for the first time?
Thanks
EDIT:
I've just opened the XAP file with WinRar and there's no "Kits" folder so I guess that my problem is how to make it add the folder to the XAP file.
I think you have to add the folder and the file to your project (i assume you are using Visual Studio). Try rightclick on your solution and add an existing object (in this case your wav file).
Did you set the build action of the wav file to "Content"? Right click on the WAV file --> properties --> build action == content.
Try this:
Uri uri = new Uri("Kits/TestKit_128/bass_126.wav", UriKind.Relative);//Above the Kits folder only the project itself.
StreamResourceInfo sr = Application.GetResourceStream(uri);
try
{
using (Stream stream = sr.Stream)
{
//working here with your data image or wav or whatever you want from URI
}
}
catch (Exception)
{
}
This is for resource inside project and working good for me. Also prevoius note about "Content" is right, it wouldn't work without it. I think the problem is double-slashes in address.

Categories

Resources