Read the content of an xml file within a zip package

I am required to read the contents of an .xml file using the Stream (Here the xml file is existing with in the zip package). Here in the below code, I need to get the file path at runtime (here I have hardcoded the path for reference). Please let me know how to read the file path at run time.

I have tried to use string s =entry.FullName.ToString(); but get the error "Could not find the Path". I have also tried to hard code the path as shown below. however get the same FileNotFound error.

string metaDataContents;
using (var zipStream = new FileStream(@"C:\OB10LinuxShare\TEST1\Temp" + "\\"+zipFileName+".zip", FileMode.Open))
using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read))
{
    foreach (var entry in archive.Entries)
    {
        if (entry.Name.EndsWith(".xml"))
        {
            FileInfo metadataFileInfo = new FileInfo(entry.Name);
            string metadataFileName = metadataFileInfo.Name.Replace(metadataFileInfo.Extension, String.Empty);
            if (String.Compare(zipFileName, metadataFileName, true) == 0)
            {
                using (var stream = entry.Open())
                using (var reader = new StreamReader(stream))
                {
                    metaDataContents = reader.ReadToEnd();
                    clientProcessLogWriter.WriteToLog(LogWriter.LogLevel.DEBUG, "metaDataContents : " + metaDataContents);
                }
            }
        }
    }
}

I have also tried to get the contents of the .xml file using the Stream object as shown below. But here I get the error "Stream was not readable".

Stream metaDataStream = null;
string metaDataContent = string.Empty;
using (Stream stream = entry.Open())
{                                
    metaDataStream = stream;
}
using (var reader = new StreamReader(metaDataStream))
{
    metaDataContent = reader.ReadToEnd();
}

Kindly suggest, how to read the contents of the xml with in a zip file using Stream and StreamReader by specifying the file path at run time

Jon Skeet
people
quotationmark

Your section code snippet is failing because when you reach the end of the first using statement:

using (Stream stream = entry.Open())
{                                
    metaDataStream = stream;
}

... the stream will be disposed. That's the point of a using statment. You should be fine with this sort of code, but load the XML file while the stream is open:

XDocument doc;
using (Stream stream = entry.Open())
{                                
    doc = XDocument.Load(stream);
}

That's to load it as XML... if you really just want the text, you could use:

string text;
using (Stream stream = entry.Open())
{                                
    using (StreamReader reader = new StreamReader(stream)
    {
        text = reader.ReadToEnd();
    }
}

Again, not how this is reading before it hits the end of either using statement.

people

See more on this question at Stackoverflow