Reputation: 348
I am trying to create a temporary file then change the temporary file to a .dotx that I have embedded into my C# program in Visual Studio. The code that I have below does not work correctly, the third line of Code where I try to reference my File in the Namespace.Properties.Resources.Myfile returns a build error saying there is no definition for the call.
Does anyone know of a better way to access this file in the folder I need.
string fileName = System.IO.Path.GetTempFileName(); // create a temp file
fileName = Path.ChangeExtension(fileName,"dotx"); //change the ext to dotx
File.WriteAllBytes(fileName, NameSpace.Properties.Resources.MyFile.dotx);
//This line of code returns the build error
Upvotes: 0
Views: 533
Reputation: 53
If you want to use File.WriteAllBytes you have to open your existed file, read it to byte array and than pass that array into File.WriteAllBytes
using (var filestream = File.Open(YOUR_EXISTED_PATH, FileMode.Open))
{
byte[] buffer = new byte[filestream.Length];
filestream.Read(buffer, 0, (int) filestream.Length);
File.WriteAllBytes(YOUR_NEW_PATH, buffer);
}
But I like previous solution more.
Upvotes: 0
Reputation: 6562
What about
public void WriteResourceToFile(string resourceName, string fileName)
{
using(var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
using(var file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
resource.CopyTo(file);
}
}
}
Upvotes: 1