I try to open a resourcefile in C# using this line, I can't see why this not working. I have tried to use build action = "embedded resource" and "none". I have tried all ways of copy to output directory. Do I need some special way of opening up resourcefiles to fileStream with c#?
public bool openFileStream()
{
FileStream mFileStream;
String[] s=System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
String mFilename =null;
for (int i = 0; i < s.Length;i++ )
{
s[i] = s[i].Replace(".", "\\");
if (s[i].Contains("sju_tre_g_i"))
{
s[i] = s[i].Substring(0, s[i].Length - 4);
s[i] = s[i] + ".wav";
mFilename = s[i];
}
System.Diagnostics.Debug.WriteLine(i + "___Outputname:" + mFilename);
}
System.Diagnostics.Debug.WriteLine(mFilename);
try{
mFileStream = File.Open(mFilename,FileMode.Open );
return true;
}
catch(Exception)
{
return false;
}
}
EDIT not duplicate In the duplicate there is just to open a text-file. It is the adress to use to FileStream mFileStream; mFileStream=File.Open("WindowsFormsApplication2\Resources\sju_tre_g_i.wav",FileMode.Open );
If you want to open an wav file from the resouces you can do this.
using (var steam = Properties.Resources.sju_tre_g_i)
{
// do something
}
Just be aware that this isn't a FileStream
but an UnmanagedMemoryStream
. (But as the ressource library is loaded into memory anyway it shouldn't make a difference?)
If you want to ensure a directory exists and you want to open a file when it exists and create it when it doesn't you can do the following.
var path = @"C:\mypath\myfile.txt";
Directory.CreateDirectory(path);
using (var stream = File.Open(path, FileMode.OpenOrCreate))
{
// do something
}
You can also use an relative path if you like.