Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

C# - Urgent. -- Get a file from the assembly and pass it to the FileStream class

Posted on 2006-11-16
5
Medium Priority
?
442 Views
Last Modified: 2008-01-09
Hi ,

This is very urgent. I have a file as an embedded resource. I want to read the file and pass it to the GZipStream class. There are 2 ways in which the GZipStream accepts :-

1) As a memoryStream
2) As a FileStream.

The Embedded file is a compressed file.

1) I have test it with the FileStream method when the copressed file is present on the local.
But how do I read an embedded resource as a FileStream ?

2) I have used the Assembly.Load("assemblyName").GetManifestResourceStream("FileName");
I passed this to a StreamReader but the data is getting corrupted.
I also used the BufferedStream with the same result.

hence my instinct is -- since I know that the FileStream works -- somehow to get the embedded resource from the Assembly as a FileStream, then the remaining code would work. But how to do that ??

there is GetFile() method which returns a FileStream but currently its giving a null value.

Assembly.Load("StylesheetLTC").GetFile("nameOfFile");

Any help ????

thanks,

0
Comment
Question by:paromitabanerjee
  • 3
5 Comments
 
LVL 22

Expert Comment

by:cookre
ID: 17962303
string AppPath=Assembly.GetExecutingAssembly().Location;
Assembly ThisAssembly=Assembly.LoadFrom(AppPath);
System.IO.Stream fs=ThisAssembly.GetManifestResourceStream("name.embeddedresourcename");
StreamReader x=new StreamReader(fs);
WholeFile=x.ReadToEnd();
x.Close();
fs.Close();
0
 

Author Comment

by:paromitabanerjee
ID: 17962537
Hi cookre,

Thanks for the prompt reply. I had already tried StreamReader, while compiling it doesn't give an error. As I said, the data coming back is a compressed data. So while decompressing, it is giving me InvalidDataException.

But if I decompress the same file in another project but using the FileStream object -- it runs perfectly and gives back the proper decompressed data.

My code for decompressing :

        public static String GetXSL(String nameOfFile)
        {
            String str = "";
            try
            {
                  string nameoffile = "StylesheetLTC50." + nameOfFile;
                    try
                    {
                      //   fstr = (Assembly.Load("StylesheetLTC50")).GetFile(nameOfFile);
                        fstr = (FileStream)(Assembly.Load("StylesheetLTC50").GetManifestResourceStream(nameoffile));
                    }catch(Exception ex)
                    {
                        Console.WriteLine("FileStream Exception == "+ex);
                    }
                    // The StreamReader is not giving proper data -- the GzipStream throws an exception
                    StreamReader stread = new StreamReader(Assembly.Load("StylesheetLTC50").GetManifestResourceStream(nameoffile));                                                                  
                    strData = stread.ReadToEnd();
                       
                     // So now we pass the byte to the MemoryStream.  
                    MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetByte(strData));                

                    GZipStream compressedZipStream = new GZipStream(fstr, CompressionMode.Decompress);
                     int offset = 0;
                     int totalBytes = 0;
                     byte[] smallBuffer = new byte[(ms.Length + 230000)];
                 
                     try
                     {
                         while (true)
                         {
                             int bytesRead = compressedZipStream.Read(smallBuffer, 0, smallBuffer.Length);
                             if (bytesRead == 0)
                             {
                                 break;
                             }
                             offset += bytesRead;
                             totalBytes += bytesRead;
                         }
                     }catch(Exception exc)
                     {
                         Console.WriteLine("Exception == "+exc);
                     }
                     compressedZipStream.Close();

           
                     GZipStream ccompressedZipStream = null;
                     // Decompress the file contents
                     ccompressedZipStream = new GZipStream(fstr, CompressionMode.Decompress);                                                          
                     byte[] bufferrr = new byte[totalBytes];
                     try
                     {
                         ccompressedZipStream.Read(bufferrr, 0, totalBytes);
                     }catch(Exception ex)
                     {
                         Console.WriteLine("The read line is throwing an error == "+ex);
                     }
                     stread.Close();
                     ccompressedZipStream.Close();                    
                     Console.ReadLine();

                      str = System.Text.Encoding.UTF8.GetString(bufferrr);
                      Console.WriteLine("str="+ str);

                                 
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception == " + ex);
            }

            return str;
        }

Is something wrong with the code ???? especially the part where I am converting the string to bytes ??

 thanks,
0
 

Author Comment

by:paromitabanerjee
ID: 17962672
Can someone please help. this is urgent ............
0
 
LVL 12

Accepted Solution

by:
sumix earned 2000 total points
ID: 17963294
Hi,
I guess that you cannot decompress the embedded file because GetManifestResourceStream method returns a memorystream and this cannot be converted to a FileStream. Therefore, fstr is null and compressedZipStream is not valid.

Here's a way that should work:

// this is how compressedZipStream can be created:
GZipStream compressedZipStream = new GZipStream(asb.GetManifestResourceStream(nameoffile), CompressionMode.Decompress);

// i choose here to read one byte at a time and put it in a FileStream
FileStream strOut = File.Create(@"uncompressed.txt");
int bt;
while ((bt = compressedZipStream.ReadByte()) != -1)
            strOut.WriteByte((byte)bt);
compressedZipStream.Close();
strOut.Close();

You can check now that "uncompressed.txt" is created ok.
0
 

Author Comment

by:paromitabanerjee
ID: 17965279
Hi sumix,

yup this worked gt8 !!!

I was thinking that GZipStream accepts only a memoryStream and trying to assign the same to it.
Thanks for ur help..... I had been breaking my head at this for a day !! :)



0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

824 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question