Search file path C#?

Asked

Viewed 1,505 times

1

I need to find a file path .wav in C#. I can find and execute the .wav with the complete path "c: caminhox...", however, I need the application to find the file in any directory that he is.

I tried to do it this way:

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

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

but he can’t find the Alarm wav., ask:

  • What is missing?
  • There’s another way to do it?
  • Automatically find? how so

  • Without having the complete path, I was with the project on my flash drive ("F: PATH ON THE THUMB DRIVE"), then I switched to a directory on my machine and it does not find the file because it is no longer in the same path... The file is in the project folder, but it does not find

  • If you have to inform a valid path to run, guess the application cannot, if you can put this file next to the executable and take the path of the executable and pass the name of the wav!? maybe this will solve your problem right away.

  • is a Windows Forms application?

  • That’s what I’m trying to do... Yeah, it’s WF

  • If you have already placed the file with the executable?

  • Yes, it’s in the case Resources

Show 3 more comments

2 answers

0

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

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 the file:

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

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

inserir a descrição da imagem aqui

  • 2

    The SoundPlayer just needs the way I think FileInfo is unnecessary.

0

Normally, the path to files without any denomination is always the path that starts in the executable location of the application itself,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 for anywhere your app is located.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.