Hey there

So, i got a website, and i want a textbox to load a .txt file loaded on my site, so it doesnt need to be downloaded, but simply just streamed to the textbox.text

for example google.com/textfile.txt, and when i click a button it would load the content of the txt file from the site
how can i do this in c#?

Hope u can follow me


Recommended Answers

All 6 Replies

Something like this should work:

Uri myUrl = new Uri("file://google.com/textfile.txt");
FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(myUrl);
FileWebResponse myFileWebResponse =(FileWebResponse)myFileWebRequest.GetResponse();
Stream receiveStream=myFileWebResponse.GetResponseStream();
StreamReader readStream = new StreamReader( receiveStream );
char[] readBuffer = new Char[256];
int count = readStream.Read( readBuffer, 0, 256 );
StringBuilder sb = new StringBuilder();
while (count > 0) {
    sb.Append(readBuffer, 0, count);
    count = readStream.Read(readBuffer, 0, 256);

myTextBox.Text = sb.ToString();

I'd put lines 1-14 in a method of its own and return the StringBuilder.ToString() response (and pass in the URI).

Thanks for the reply, however im facing a problem at line two saying "Unable to cast object of type 'System.Net.HttpWebRequest' to type 'System.Net.FileWebRequest'." :P

Did you use "file:..." or "http:"? Since you are looking to read a file and not a HTML page, use "file:".

doing that gives me an error at line three saying "The network path was not found."

however when i google the file, its clearly defining it as http :P

Change all the File... to Http... (so FileWebRequest becomes HttpWebRequest).

commented: Thanks for helping me :) +3

Thanks! that worked :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.