Search for C # file path?

1

I need to find the path of a .wav file in C# . I can find and run .wav with the full path "c: \\ pathx ...", however, I need the application to find the file in any directory it is strong>.

I tried to do this:

var file = new FileInfo(Path.Combine(Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location), @"Alarm.wav"));

SoundPlayer soundPlayer = new SoundPlayer(file.ToString());            
soundPlayer.Play();

But he can not find Alarm.wav , I ask:

  • What's missing?
  • Is there another way to do this?
asked by anonymous 09.12.2017 / 14:32

2 answers

0

If the file is in the same folder as the executable, use:

FileInfo file = new FileInfo(Path.Combine(Application.StartupPath, @"Alarm.wav"));

if (file.Exists)
{
    SoundPlayer soundPlayer = new SoundPlayer(file.FullName);            
    soundPlayer.Play();
}
else
{
  //arquivo wav nao existe
}

If you want to search for the file:

FileInfo[] files = new DirectoryInfo(Application.StartupPath).GetFiles("Alarm.wav", SearchOption.AllDirectories);

And make sure that the file is published when compiling the project, changing the Copy to Output Directory option you can set Copy Aways or Copy if newer :

    
09.12.2017 / 15:01
0

Normally, the path to files without any naming is always the path that starts in the application's own executable location, for example:

C:\...\PastaDoPrograma\Pasta\Arquivo.arq
Se eu quiser encontrar esse arquivo, simplesmente digito:
string path = "Pasta\Arquivo.arq";
if(File.Exist(path))
File.OpenRead(path);

And that's it. This should work wherever your application is located.

    
22.12.2017 / 22:28