Thursday, November 19, 2015

File upload in Resource (.resx)


I was working on Azure web job wherein I had to put an excel in the solution and use it after getting deployed. I was struggling with finding the path of the file, tried with “~”, “..\” and all other options suggested over the internet to vain. Later I was introduced to uploading a file in the .resx and fetching/accessing the file just like any other resource.
Below is the step by step procedure for doing so –
a.      Add .resx file in your solution, if not already





b.      Instead of Strings, select Files for upload



c.      Click on Add Resource, select All Files and add file. Save the resx. You will see the uploaded file in the solution under Resource folder
In the below screenshot, you will see that I have added .xlsx file.



d.      The next most important step here is to right click on the file which we have uploaded and click on Properties, set the “Build Action” to “Embedded Resource”. This step will make sure that the executing assembly has the information of this file.



e.      Now the next step would be to access this file in the code. Below is the code for the same,
Assembly assembly = Assembly.GetExecutingAssembly();
Stream st = assembly.GetManifestResourceStream("<SolutionName>.Resources.<FileNameWithExtension>");
           
if (st.CanSeek)
{
  st.Position = 0;
}
Note:
a.      The GetManifestResourceStream method needs an exact path of the file in the form of a hierarchy ie SolutionName.Resources.FileName.FileNameExtension
The data in the uploaded file is now available in the stream. We can now use it as per our need.
Please leave your feedback and queries in the comments section. Thank you!