Download Files From Resource Library in c# .net

血红的双手。 提交于 2019-12-11 13:36:34

问题


I am developing an application where from several screens user has to download a sample file(excel) to work with. What will be the preferable way to do so.

What i am doing is

Placing the file in the directory where application is executing and download the files using Application.StartupPath. This does not sounds like a very good solution. As at anytime user could edit the files or delete the files or such things.

What i want to do is

I want to add all the files in my resources and download files from the resources. I add the files but i need a little help on how to download it from resources.

Thanks


回答1:


you can use:

 class ResourceHelper
    {
           public static void MakeFileOutOfAStream(string stream, string filePath)
            {
                using(var fs = new FileStream(filePath,FileMode.Create,FileAccess.ReadWrite))
                {
                    CopyStream(GetStream(stream), fs);
                }
            }

            static void CopyStream(Stream input, Stream output)
            {
                byte[] buffer = new byte[32768];
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, read);
                }
            }
 static Stream GetStream(string stream)
        {
             return Assembly.GetExecutingAssembly().GetManifestResourceStream(stream));

        }
    }

and with stream pass the complete name of you resource, that is the namespace + the resource file name ( evantual folder are to be considered as namespace part ) case sensitive. Remember to flag the file in your project as embedded resource.




回答2:


You can use Assembly.GetManifestResourceStream and save the stream in some file to work with it. Here is a simple example:

using (var resource = Assembly.GetManifestResourceStream("resource_key"))
using (var file = File.OpenWrite(filename))
{
    var buffer = new byte[1024];
    int len;
    while ((len = resource.Read(buffer, 0, buffer.Length)) > 0)
    {
        file.Write(buffer, 0, len);
    }  
}

Please note. There is no way to store the file changes back to the resources.



来源:https://stackoverflow.com/questions/10517567/download-files-from-resource-library-in-c-sharp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!