Cannot locate the wav file in the root folder of the project - c#

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

Related

Load External Files with C# (From Resource Folder)

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);
}

c# Add Soundfile to Setup and direct to file path

I want to create a SetupFile for my project. I have two sounds that I use... that's my current code (which works fine when I debug):
SoundPlayer clckSound = new SoundPlayer(#"C:\Users\My Name\Downloads\Button Push.wav");
SoundPlayer wonSound = new SoundPlayer(#"C:\Users\My Name\Downloads\Applause.wav");
Inside my Setup Project in the "Application Folder" I created another folder named "Assets" where I put the two sound files.
I tried it with the following code which didnt work.
SoundPlayer clckSound = new SoundPlayer(Application.StartupPath + "\\Assets\\Button Push.wav");
SoundPlayer wonSound = new SoundPlayer(Application.StartupPath + "\\Assets\\Applause.wav");
How do I specify the file path in my code so that the sounds get played properly after installation of the Setup file?
Thanks for your help!

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 ;

playing .wav file with C#

I'm trying to play a .Wav file thats located in a folder inside my project.
The sound file is located on "Resource/Sounds/slot_roll_on.Wav"
The resource folder is a folder I created myself, in the root of the project.
This is the code I'm using to run the .wav file
Assembly a = Assembly.GetExecutingAssembly();
Stream s = a.GetManifestResourceStream("kisscam.g.resources.Resources.Sounds.slot_roll_on.wav");
SoundPlayer snd = new SoundPlayer(s);
snd.Play();
I couldn't get the sound to play, I keep getting the windows sound for sound not found.
Somewhere on stack overflow I found this code to find what the right assembly path should be.
Assembly a = Assembly.GetExecutingAssembly();
string[] resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
int i;
for (i = 0; i < resourceNames.Length; i++)
{
MessageBox.Show(resourceNames[i]);
}
It output these 2 paths
kisscam.Properties.Resources.resources
and
kissscam.g.resources
I tried using them both, but none of them works.
Anyone know what I'm doing wrong ?
Add your Wav file to resources by going to your Project Properties --> Resources Select Audio and Browse to the file. You will then be able to see it as part pf Propeties.Resources. It will add it to a Resources Folder where you can set it to embedded or leave it as is, which is set as content
Accessed like this
private void button1_Click(object sender, EventArgs e)
{
SoundPlayer snd = new SoundPlayer( Properties.Resources.tada);
snd.Play();
}
If you want to add music in your program by playing your .wav file in projects. Then you have to add the .wav file like this.
using System.Media; // write down it at the top of the FORM
SoundPlayer my_wave_file = new SoundPlayer("F:/SOund wave file/airplanefly.wav");
my_wave_file.PlaySync(); // PlaySync means that once sound start then no other activity if form will occur untill sound goes to finish
Remember that you have to write the path of the file with forward slashes (/) format, don't use back slashes () during giving a path to the file, otherwise you will get an error
Currently I know two ways to do so, see below:
Use file path
First put the file in the root folder of the project, then no matter you run the program under Debug or Release mode, the file can both be accessed for sure. Next use the class SoundPlayer to paly it.
var basePath = System.AppDomain.CurrentDomain.BaseDirectory;
SoundPlayer player = new SoundPlayer();
player.SoundLocation = Path.Combine(basePath, #"./../../Reminder.wav");
player.Load();
player.Play();
Use resource
Follow below animate, add "Exsiting file" to the project.
SoundPlayer player = new SoundPlayer(Properties.Resources.Reminder);
player.Play();
The strength of this way compared to the other is:
Only the folder "Release" under the "bin" directory need to be copy when run the program.

Load local HTML file in a C# WebBrowser

In my app I have a WebBrowser element.
I would like to load a local file in it.
I have some questions:
Where to place the HTML file (so that it will also be installed if a user executes the setup)
how to reference the file? (e.g. my guess is the user's installation folder would not always be the same)
EDIT
I've added the HTML file to my project.
And I have set it up so that it gets copied to output folder.
When I check it it is present when run: \bin\Debug\Documentation\index.html
However when I do the following I get a 'Page cannot be displayed' error in the webbrowser element.
I use the following code to try to display the HTML file in the Webbrowser.
webBrowser1.Navigate(#".\Documentation\index.html");
Do a right click->properties on the file in Visual Studio.
Set the Copy to Output Directory to Copy always.
Then you will be able to reference your files by using a path such as #".\my_html.html"
Copy to Output Directory will put the file in the same folder as your binary dlls when the project is built. This works with any content file, even if its in a sub folder.
If you use a sub folder, that too will be copied in to the bin folder so your path would then be #".\my_subfolder\my_html.html"
In order to create a URI you can use locally (instead of served via the web), you'll need to use the file protocol, using the base directory of your binary - note: this will only work if you set the Copy to Ouptut Directory as above or the path will not be correct.
This is what you need:
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));
You'll have to change the variables and names of course.
quite late but it's the first hit i found from google
Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:
//using System.IO;
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);
Note that the file:/// scheme does not work on the compact framework, at least it doesn't with 5.0.
You will need to use the following:
string appDir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, #"Documentation\index.html"));
Place it in the Applications setup folder or in a separte folder beneath
Reference it relative to the current directory when your app runs.
Somewhere, nearby the assembly you're going to run.
Use reflection to get path to your executing assembly, then do some magic to locate your HTML file.
Like this:
var myAssembly = System.Reflection.Assembly.GetEntryAssembly();
var myAssemblyLocation = System.IO.Path.GetDirectoryName(a.Location);
var myHtmlPath = Path.Combine(myAssemblyLocation, "my.html");
What worked for me was
<WebBrowser Source="pack://siteoforigin:,,,/StartPage.html" />
from here. I copied StartPage.html to the same output directory as the xaml-file and it loaded it from that relative path.
Windows 10 uwp application.
Try this:
webview.Navigate(new Uri("ms-appx-web:///index.html"));
Update on #ghostJago answer above
for me it worked as the following lines in VS2017
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));
I have been trying different answers from here, but managed to derive something working, here it is:
1- Added the page in a folder i created at project level named WebPagesHelper
2- To have the page printed by webBrowser Control,
string curDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
var uri = new Uri(curDirectory);
string myFile = Path.Combine(uri.AbsolutePath, #"WebPagesHelper\index.html");
Uri new_uri = new Uri(myFile);
i had to get the assembly path, create a first uri to get an absolute path without the 'file://' attached, next i combined this absolute path with a relative path to the page in its folder, then made another URI from the result.
Then pass this to webBrowser URL property webBrowser.URL = new_uri;

Categories