manav inder
manav inder

Reputation: 3601

Download Files From Resource Library in c# .net

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

Upvotes: 1

Views: 2410

Answers (2)

Felice Pollano
Felice Pollano

Reputation: 33242

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.

Upvotes: 1

ie.
ie.

Reputation: 6101

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.

Upvotes: 1

Related Questions