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.
Related
This question already has answers here:
FileStream.Write not Writing to File
(2 answers)
Closed 2 years ago.
I have an easy function, which should receive Stream object and write it to the file "result.txt"
Here is my function:
public void WriteToFile(Stream stream)
{
StreamReader reader = new StreamReader(stream);
stream.Position = 0;
FileInfo f = new FileInfo("result.txt");
FileStream fs = f.Create();
stream.CopyTo(fs);
stream.Position = 0;
var text = reader.ReadToEnd();
Console.WriteLine(text);
}
But I have an issue with writing to the file. In result - file is empty. But, I receive output in console from this line of code:
var text = reader.ReadToEnd();
Console.WriteLine(text);
In console I get simple and short json output
{"startAt":0,"maxResults":0,"total":472,"issues":[]}
This function works fine with other, larger streams, but this 52 Byte stream just does not want to be written to the file. What am I doing wrong?
you don't need any StreamReader, just do it like this:
public void WriteToFile(Stream stream)
{
stream.Seek(0, SeekOrigin.Begin);
using(var fs = new FileStream("/path/to/file", FileMode.OpenOrCreate))
{
stream.CopyTo(fs);
}
}
//var memoryStream...
//...
WriteFoFile(memoryStream);
You can use something like this:
public void WriteToFile(Stream stream)
{
var writer = new System.IO.StreamWriter("result.txt");
StreamReader reader = new StreamReader(stream);
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine(line);
}
var text = reader.ReadToEnd();
writer.Close();
reader.Close();
Console.WriteLine(text);
}
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.
Because I have no experience with sockets and I don't know how to make one, I have this code:
public void getGameInfo()
{
string content;
do
{
WebClient client = new WebClient();
client.DownloadFile(fileadress, filename);
client.Dispose();
StreamReader reader = new StreamReader(filename);
content = reader.ReadToEnd();
reader.Close();
} while (content == "");
File.Delete(filename);
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = zeilen[0];
gameInfo = new string[line.Length-1];
Array.Copy(lines, 1, gameInfo, 0, lines.Length-1);
}
It connects to a Apache server with a .txt file and reads it. But if too many Programms (three) uses the code, it will throw a WebException.
So is there a way to improve this, or a guide to make a socket for this?
Edit 1:
And what if I want to write to the file like this function?
public void setSpielInfo(int line, string input)
{
WebClient client = new WebClient();
string content;
do
{
client.DownloadFile(gameadress, filename);
StreamReader reader = new StreamReader(filename);
content = reader.ReadToEnd();
reader.Close();
} while (content == "");
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
lines[zeile+1] = input;
byte[] bytearray = Encoding.ASCII.GetBytes(string.Join(Environment.NewLine, lines)); // I've read that byte arrays are faster than string arrays
FileStream writer = new FileStream(filename, FileMode.Truncate);
writer.Write(bytearray, 0, bytearray.Length);
writer.Close();
client.UploadFile(ftpAdress, filename);
client.Dispose();
File.Delete(filename);
}
You want to read string, right? So why do you download file?
string content;
// Do not dispose explicitly, wrap into using instead
using (WebClient client = new WebClient()) {
content = client.DownloadString(fileadress);
}
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = lines.FirstOrDefault(); // 1st line
gameInfo = lines.Skip(1).ToArray(); // all the others
You can further shorten the code into
using (WebClient client = new WebClient()) {
var lines = client
.DownloadString(fileadress)
.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = lines.FirstOrDefault();
gameInfo = lines.Skip(1).ToArray();
}
Edit: again, what do you actually want to perform: download a string, write file, upload the file:
string content;
// Do not dispose explicitly, wrap into using instead
using (WebClient client = new WebClient()) {
// Download string (text)
content = client.DownloadString(fileadress);
// Write the text to file (override existing if it is)
File.WriteAllText(filename, content);
// Upload file
// think on uploading the string - client.UploadString(ftpAdress, content);
client.UploadFile(ftpAdress, filename);
}
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = lines.FirstOrDefault(); // 1st line
gameInfo = lines.Skip(1).ToArray(); // all the others
As the further improvent think on working with string not files:
using (WebClient client = new WebClient()) {
// Download string (text)
content = client.DownloadString(fileadress);
client.UploadString(ftpAdress, content);
}
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();
I'm using the following code to grab a wmv file through a WebResponse. I'm using a thread to call this function:
static void GetPage(object data)
{
// Cast the object to a ThreadInfo
ThreadInfo ti = (ThreadInfo)data;
// Request the URL
WebResponse wr = WebRequest.Create(ti.url).GetResponse();
// Display the value for the Content-Length header
Console.WriteLine(ti.url + ": " + wr.Headers["Content-Length"]);
string toBeSaved = #"C:\Users\Kevin\Downloads\TempFiles" + wr.ResponseUri.PathAndQuery;
StreamWriter streamWriter = new StreamWriter(toBeSaved);
MemoryStream m = new MemoryStream();
Stream receiveStream = wr.GetResponseStream();
using (StreamReader sr = new StreamReader(receiveStream))
{
while (sr.Peek() >= 0)
{
m.WriteByte((byte)sr.Read());
}
streamWriter.Write(sr.ReadToEnd());
sr.Close();
wr.Close();
}
streamWriter.Flush();
streamWriter.Close();
// streamReader.Close();
// Let the parent thread know the process is done
ti.are.Set();
wr.Close();
}
The file seems to download just fine, but Windows Media Viewer cannot open the file properly. Some silly error about not being able to support the file type.
What incredibly easy thing am I missing?
You just need to download it as binary instead of text. Here's a method that should do the trick for you.
public void DownloadFile(string url, string toLocalPath)
{
byte[] result = null;
byte[] buffer = new byte[4097];
WebRequest wr = WebRequest.Create(url);
WebResponse response = wr.GetResponse();
Stream responseStream = response.GetResponseStream;
MemoryStream memoryStream = new MemoryStream();
int count = 0;
do {
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, count);
if (count == 0) {
break;
}
}
while (true);
result = memoryStream.ToArray;
FileStream fs = new FileStream(toLocalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs.Write(result, 0, result.Length);
fs.Close();
memoryStream.Close();
responseStream.Close();
}
I do not understand why you are filling MemoryStream m one byte at a time, but then writing the sr to the file. At that point, I believe the sr is empty, and MemoryStream m is never used.
Below is some code I wrote to do a similar task. It gets a WebResponse in 32K chunks at a time, and dumps it directly to a file.
public void GetStream()
{
// ASSUME: String URL is set to a valid URL.
// ASSUME: String Storage is set to valid filename.
Stream response = WebRequest.Create(URL).GetResponse().GetResponseStream();
using (FileStream fs = File.Create(Storage))
{
Byte[] buffer = new Byte[32*1024];
int read = response.Read(buffer,0,buffer.Length);
while (read > 0)
{
fs.Write(buffer,0,read);
read = response.Read(buffer,0,buffer.Length);
}
}
// NOTE: Various Flush and Close of streams and storage not shown here.
}
You are using a StreamReader and a StreamWriter to transfer your stream, but those classes are for handling text. Your file is binary and chances are that sequences of CR, LF and CR LF may get clobbered when you transfer the data. How NUL characters are handled I have no idea.