Usage of StreamReader in C# - c#

I want to read a file data.json and convert it to a string.
My code is this one:
String json = null;
using (StreamReader sr = new StreamReader("data.json"))
{
json = sr.ReadToEnd();
}
but Visual Studio tells me that StreamReader does not expect a String as constructor argument.
How can I tell StreamReader that I want to read the file data.json?

Actually StreamReader supports constructor which accepts file path for most platforms, but not all. But anyway - simply use File.ReadAllText:
string json = File.ReadAllText("data.json");
It creates StreamReader internally (link to source):
using (var sr = new StreamReader(path, encoding))
return sr.ReadToEnd();
UPDATE: You can always pass stream to StreamReader. Use FileStream to open stream for reading file, and then pass it to StreamReader:
string json = null;
using (var stream = new FileStream("data.json", FileMode.Open))
using (var reader = new StreamReader(stream))
json = reader.ReadToEnd();

Related

Changing from MemoryStream to Stream in C#

Below is the code where I am passing memory stream and reading it and doing the necessary operation afterwards. Now the requirement has changed and instead of Memory stream, I will be passing Stream and that starts giving me error. I would like to know how can I handle the below method if contents returned here is of Stream type. Now it works fine when my contents is of type MemoryStream.
public async Task<string> ReadStream(string containerName, string digestFileName, string fileName, string connectionString)
{
string data = string.Empty;
string fileExtension = Path.GetExtension(fileName);
var contents = await DownloadBlob(containerName, digestFileName, connectionString);
if (fileExtension == ".gz")
{
using (var unzipper = new GZipStream(contents, CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(unzipper, Encoding.UTF8))
{
data = reader.ReadToEnd();
}
}
}
else
{
data = Encoding.UTF8.GetString(contents.ToArray());
}
return data;
}
I'm going to assume the issue is contents.ToArray(), since Stream desn't have a ToArray() method.
In this case, you'll be better off using a StreamReader:
using (var reader = new StreamReader(contents))
{
data = reader.ReadToEnd();
}
StreamReader uses Encoding.UTF8 by default, but you can specify it explicitly if you want: new StreamReader(contents, Encoding.UTF8).
You'll note that you're already doing this a few lines above, to read from the unzipper stream.

StreamReader save ReadLine to string and use it in if

Hi I want to save the output from reader.ReadToEnd() to a string and check if the string is "Access" but I don't know how to do it.
string url = "https://mywebsite.com/check.php";
Stream mystream = client.OpenRead(url);
StreamReader reader = new StreamReader(mystream);
Console.WriteLine(reader.ReadToEnd()); //The text will be "Access"
//Pseudecode start
string line = reader.ReadToEnd();
if (line == "Access")
{
useraccess = true;
Console.WriteLine("Done!");
}
mystream.Close();
You are reading the stream twice without any sort of reset, it would be more advisable to read it only once. Also you should be disposing of your stream and streamreader appropriately. See the following:
string url = "https://mywebsite.com/check.php";
string remoteData = null;
using (Stream mystream = client.OpenRead(url))
using (StreamReader reader = new StreamReader(mystream))
remoteData = reader.ReadToEnd();
Console.WriteLine(remoteData); //The text will be "Access"
//Pseudecode start
if (remoteData == "Access")
{
useraccess = true;
Console.WriteLine("Done!");
}
This should work under the assumption that ReadToEnd() is returning what you wanted it to return. I don't know what your endpoint looks like so I can't verify.

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
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, note how this is reading before it hits the end of either using statement.
Here is a sample of how to read a zip file using .net 4.5
private void readZipFile(String filePath)
{
String fileContents = "";
try
{
if (System.IO.File.Exists(filePath))
{
System.IO.Compression.ZipArchive apcZipFile = System.IO.Compression.ZipFile.Open(filePath, System.IO.Compression.ZipArchiveMode.Read);
foreach (System.IO.Compression.ZipArchiveEntry entry in apcZipFile.Entries)
{
if (entry.Name.ToUpper().EndsWith(".XML"))
{
System.IO.Compression.ZipArchiveEntry zipEntry = apcZipFile.GetEntry(entry.Name);
using (System.IO.StreamReader sr = new System.IO.StreamReader(zipEntry.Open()))
{
//read the contents into a string
fileContents = sr.ReadToEnd();
}
}
}
}
}
catch (Exception)
{
throw;
}
}

Serializing a memorystream object to string

Right now I'm using XmlTextWriter to convert a MemoryStream object into string. But I wan't to know whether there is a faster method to serialize a memorystream to string.
I follow the code given here for serialization - http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp
Edited
Stream to String
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
string content = sr.ReadToEnd();
SaveInDB(ms);
}
String to Stream
string content = GetFromContentDB();
byte[] byteArray = Encoding.ASCII.GetBytes(content);
MemoryStream ms = new MemoryStream(byteArray);
byte[] outBuf = ms.GetBuffer(); //error here
using(MemoryStream stream = new MemoryStream()) {
stream.Position = 0;
var sr = new StreamReader(stream);
string myStr = sr.ReadToEnd();
}
You cant use GetBuffer when you use MemoryStream(byte[]) constructor.
MSDN quote:
This constructor does not expose the
underlying stream. GetBuffer throws
UnauthorizedAccessException.
You must use this constructor and set publiclyVisible = true in order to use GetBuffer
In VB.net i used this
Dim TempText = System.Text.Encoding.UTF8.GetString(TempMemoryStream.ToArray())
in C# may apply

How to take a stringbuilder and convert it to a streamReader?

How to take a stringbuilder and convert it to a stream?
SO my stringbuilder has to be converted into a :
StreamReader stream = ????
Update
I tried using a stringreader like:
StringReader sr = new StringReader(sb.ToString());
StreamReader stream = new StreamReader(sr);
but that doesn't work?
Use ToString to convert the StringBuilder into a String, and use a StringReader to wrap the String as a Stream.
If using a StreamReader is a requirement then convert the string to a memory stream and then create a new StreamReader using that object:
StreamReader reader= new StreamReader(
new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString())));

Categories