.NET: Open files, which are embedded in a resource file - c#

How can I open files, which are embedded in a resource file, like a file on the harddisk (with an absolute path) ?

Suppose that you have the test.xml file embedded into the assembly. You could use the GetManifestResourceStream method to obtain a stream pointing towards the contents:
class Program
{
static void Main()
{
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("ProjectName.test.xml"))
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
This way the contents of the file is read into memory. You can also store it to the harddisk and then access by absolute path but this might not be necessary as you already have the contents of the file.

Related

Reading an embedded text file

I have created a full project which works perfectly. My problem concerns the setup project. When I use it on another computer, the text file cannot be found even if they are inside the resource folder during the deployment!
How can I ensure that my program will find those text files after installing the software on another computer!
I have been looking for this solution but in vain. Please help me sort this out. If I can get a full code that does that i will be very happy!
FIrst set the build action of the text file to "EmbeddedResource".
Then to read the file in your code:
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "AssemblyName.MyFile.txt";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}
}
If you can't figure out the name of the embedded resource do this to find the names and it should be obvious which your file is:
assembly.GetManifestResourceNames();
This is assuming you want the text file to be embedded in the assembly. If not, then you might just want to change your setup project to include the text file during the installation.
Assuming you mean that you have a file in your project that you've set as an EmbeddedResource, you want
using (var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(path))
{
...
}
where path should be the assembly name followed by the relative path to your file in the project folder hierarchy. The separator character used is the period ..
So if you have an assembly called MyCompany.MyProject and then in that project you have a folder Test containing Image.jpg, you would use the path MyCompany.MyProject.Test.Image.jpg to get a Stream for it.
create this function to read whatever embedded resource text file you have :
public string GetFromResources(string resourceName)
{
Assembly assem = this.GetType().Assembly;
using (Stream stream = assem.GetManifestResourceStream(resourceName))
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}

Taking a copy of an Excel template that is saved in the Solution

I have this solution structure:
I'd like to take a copy of this template and then save a copy of it to a network drive. Using System.IO I've previously using this code to take a copy of a file:
string templateFilePath = #"\\blah\blah\blah\blah\Temp.xlsx"; //<<<< X
string exportFilePath = #"\\blah\blah\blah\blah\Results.xlsx";
File.Copy(templateFilePath, exportFilePath, true);
Because the template is saved within the solution do I still need to specify the complete pathway or is there a shorter was of referencing this file?
You'll need to specify the full path of the file or the relative path in regards to where the executable is running. So you can set targetFileName = ".\template.xlsx
another way to get the file is to mark the Build Action in the properties of the file and set it to Embedded Resource. then use the following code to get the stream. Not sure if the stream will help you or not.
Assembly asm = Assembly.GetExecutingAssembly();
string file = string.Format("{0}.Template.xlsx", asm.GetName().Name);
var ms = new MemoryStream();
Stream fileStream = asm.GetManifestResourceStream(file);

Asp.Net: Save File at Path Location

I uploaded pdf files on client side.
I passed path location to .ashx file, from this i have path location in string variable. I need to save this file in that path location.
please help.
Assuming rootPath is a variable containing the root path, and fileName is the name of the file you wish to save:
var filePath = System.IO.Path.Combine(rootPath, fileName);
I don't know what form the file exists in. If you include that, I can give better instructions on what to do with filePath from there.
using (var outputStream = File.Open(filePath, FileMode.CreateNew))
{
// write to outputStream; depends on what form your PDF file is in at this point.
}

C# Access text file in zip archive

How can I read content of a text file inside a zip archive?
For example I have an archive qwe.zip, and insite it there's a file asd.txt, so how can I read contents of that file?
Is it possible to do without extracting the whole archive? Because it need to be done quick, when user clicks a item in a list, to show description of the archive (it needed for plugin system for another program). So extracting a whole archive isn't the best solution... because it might be few Mb, which will take at least few seconds or even more to extract... while only that single file need to be read.
You could use a library such as SharpZipLib or DotNetZip to unzip the file and fetch the contents of individual files contained inside. This operation could be performed in-memory and you don't need to store the files into a temporary folder.
Unzip to a temp-folder take the file and delete the temp-data
public static void Decompress(string outputDirectory, string zipFile)
{
try
{
if (!File.Exists(zipFile))
throw new FileNotFoundException("Zip file not found.", zipFile);
Package zipPackage = ZipPackage.Open(zipFile, FileMode.Open, FileAccess.Read);
foreach (PackagePart part in zipPackage.GetParts())
{
string targetFile = outputDirectory + "\\" + part.Uri.ToString().TrimStart('/');
using (Stream streamSource = part.GetStream(FileMode.Open, FileAccess.Read))
{
using (Stream streamDestination = File.OpenWrite(targetFile))
{
Byte[] arrBuffer = new byte[10000];
int iRead = streamSource.Read(arrBuffer, 0, arrBuffer.Length);
while (iRead > 0)
{
streamDestination.Write(arrBuffer, 0, iRead);
iRead = streamSource.Read(arrBuffer, 0, arrBuffer.Length);
}
}
}
}
}
catch (Exception)
{
throw;
}
}
Although late in the game and the question is already answered, in hope that this still might be useful for others who find this thread, I would like to add another solution.
Just today I encountered a similar problem when I wanted to check the contents of a ZIP file with C#. Other than NewProger I cannot use a third party library and need to stay within the out-of-the-box .NET classes.
You can use the System.IO.Packaging namespace and use the ZipPackage class. If it is not already included in the assembly, you need to add a reference to WindowsBase.dll.
It seems, however, that this class does not always work with every Zip file. Calling GetParts() may return an empty list although in the QuickWatch window you can find a property called _zipArchive that contains the correct contents.
If this is the case for you, you can use Reflection to get the contents of it.
On geissingert.com you can find a blog article ("Getting a list of files from a ZipPackage") that gives a coding example for this.
SharpZipLib or DotNetZip may still need to get/read the whole .zip file to unzip a file. Actually, there is still method could make you just extract special file from the .zip file without reading the entire .zip file but just reading small segment.
I needed to have insights into Excel files, I did it like so:
using (var zip = ZipFile.Open("ExcelWorkbookWithMacros.xlsm", ZipArchiveMode.Update))
{
var entry = zip.GetEntry("xl/_rels/workbook.xml.rels");
if (entry != null)
{
var tempFile = Path.GetTempFileName();
entry.ExtractToFile(tempFile, true);
var content = File.ReadAllText(tempFile);
[...]
}
}

problem with opening a file in C#

What am I doing wrong in the following code?
public string ReadFromFile(string text)
{
string toReturn = "";
System.IO.FileStream stream = new System.IO.FileStream(text, System.IO.FileMode.Open);
System.IO.StreamReader reader = new System.IO.StreamReader(text);
toReturn = reader.ReadToEnd();
stream.Close();
return toReturn;
}
I put a text.txt file inside my bin\Debug folder and for some reason, each time when I enter this file name ("text.txt") I am getting an exception of System.IO.FileNotFoundException.
It is not safe to assume that the current working directory is identical to the directory in which your binary is residing. You can usually use code like the following to refer to the directory of your application:
string applicationDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string filename = System.IO.Path.Combine(applicationDirectory, text);
This may or may not be a solution for your given problem. On a sidenote, text is not really a decent variable name for a filename.
If I want to open a file that is always in a folder relative to the application's startup path, I use:
Application.StartupPath
to simply get the startuppath, then I append the rest of the path (subfolders and or file name).
On a side note: in real life (i.e. in the end user's configuration) the location of a file you need to read is seldom relative to the applications startup path. Applications are usually installed in the Program Files folder, application data is stored elsewhere.
File.ReadAllText(path) does the same thing as your code. I would suggest using rooted path like "c:......\text.txt" instead of the relative path. The current directory is not necessarily set to your app's home directory.
You can use Process Monitor (successor to FileMon) to find out exactly what file your application tries to read.
My suggestions:
public string ReadFromFile(string fileName)
{
using(System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Open))
using(System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
return = reader.ReadToEnd();
}
}
or even
string text = File.OpenText(fileName).ReadToEnd();
You can also check is file exists:
if(File.Exists(fileName))
{
// do something...
}
At last - maybe your text.txt file is open by other process and it can't be read at this moment.

Categories