How to access a binary resource in a C# application

后端 未结 3 1841
余生分开走
余生分开走 2021-01-12 03:44

I\'m trying to store an empty Access database (.mdb) as a resource in my application. I then want to write it out the file system and populate it with table definitions, et

相关标签:
3条回答
  • 2021-01-12 04:03

    You need to prefix the "empty.mdb" with the default namespace of the assembly. Something like:

    objStream = objAssembly.GetManifestResourceStream("My.Namespace.empty.mdb");
    
    0 讨论(0)
  • 2021-01-12 04:06

    You can also check the names of your resources by invoking

    string[] myResources = objAssembly.GetManifestResourceNames();
    foreach(string reso in myResources) {
       Console.WriteLine(reso);
    }
    

    Also, make sure your empty.mdb file is marked with Embedded Resource on compilation action

    alt text http://img520.imageshack.us/img520/6649/sinttuloo.png

    0 讨论(0)
  • 2021-01-12 04:20

    This will extract a binary embedded resource file ...

        /// <summary>
        /// Extracts an embedded file to local file system.
        /// </summary>
        /// <param name="resName">Resource name of embedded file. NameSpace.FileName.Extension</param>
        /// <param name="fileName">Extracted file name</param>
        public void ExtractEmbeddedFile(string resName, string fileName)
        {
            if (File.Exists(fileName)) File.Delete(fileName);
    
            Assembly assembly = Assembly.GetExecutingAssembly();
    
            using (var input = assembly.GetManifestResourceStream(resName))
            using (var output = File.Open(fileName, FileMode.CreateNew))
            {
                if (input == null) throw new FileNotFoundException(resName + ": Embedded resoure file not found");
    
                var buffer = new byte[32768];
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, read);
                }
                output.Flush();
            }
        }
    

    It's very useful for C# Unit tests that require data files where your DLLs typically run without any content files present (they may run in temporary folders created by the unit test framework).

    This has another code snippet for text files (not binary files) though it may have memory leaks as it failed to use the using statement.

    • http://www.cauldwell.net/patrick/blog/PermaLink,guid,e9a1451b-108c-4da7-8be9-2b6c2316f7b1.aspx
    0 讨论(0)
提交回复
热议问题