Search code examples
c#embedded-resource

Accessing the Files in the Resource Folder .Net 3.5


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

Solution

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