Nomistake
Nomistake

Reputation: 863

Call Resource with string variable

I would like to use the resources in my solution by passing a string variable to Properties.Resources:

string[] documents = new string[] { "one", "two", "three"};
foreach (var document in documents)
{
   extractFile(String.Format(@"C:\temp\{0}.doc",document), properties.Resources.document);
}

private void extractFile (string destinationFile, byte[] sourceFile)
{
   File.WriteAllBytes(destinationFile, sourceFile);
}

But i cannot use the string "document" for properties.Resources like this.

('Resources' does not contain a definition for 'document')

How can I make this work?

Upvotes: 0

Views: 287

Answers (2)

Nomistake
Nomistake

Reputation: 863

As a solution to the problem i zipped all needed files and added this 1 file to the resources. I extracted it to temp folder and unzipped it to the appropriate locations as needed...

Upvotes: 0

Kvam
Kvam

Reputation: 2218

You can get the resource by name like this:

string[] documents = new string[] { "one", "two", "three"};
foreach (var document in documents)
{
    var unmanagedMemoryStream = Resources.ResourceManager.GetStream(document);

    var memoryStream = new MemoryStream();
    unmanagedMemoryStream.CopyTo(memoryStream);
    memoryStream.Position = 0;
    byte[] bytes = memoryStream.ToArray();

    extractFile(String.Format(@"C:\temp\{0}.doc", document),
                bytes);
}

There are several methods available on ResourceManager that might be better suited depending on the type of the resource: GetStream, GetString or GetObject.

Upvotes: 1

Related Questions