download a word document from server using c#.net

N

nalla

iam working in a project where i need to provide a link to user such
that he can download a word Document from server (not my local pc).iam
able to do this from my localhost ,but from other pc i need to use
System.Net.WebRequest but i donot know how to use it.

code for access from localhost:


string filename="anjit.doc";

// if (filename != "")
//
// {
//
// string path = Server.MapPath(filename);
// System.Net.WebRequest
//
// System.IO.FileInfo file = new
System.IO.FileInfo(path);
//
// if (file.Exists)
//
// {
//
// Response.Clear();
//
//
Response.AddHeader("Content-Disposition", "attachment;
filename=" + file.Name);
//
//
Response.AddHeader("Content-Length", file.Length.ToString());
//
// Response.ContentType =
"application/octet-stream";
//
//
Response.WriteFile(file.FullName);
//
// Response.End();
//
// }
//
// else
//
// {
//
// Response.Write("This file does
not exist.");
//
// }
i think i have to use below code but it is not working


System.Net.WebRequest myRequest
=System.Net.WebRequest.Create("http://20.198.118.149/anjit/a.txt");
Console.WriteLine(myRequest);
 
M

Morten Wennevik

Hi nalla,

Try something like this instead

using System.Web;

WebRequest myRequest =
WebRequest.Create("http://20.198.118.149/anjit/a.txt");
WebResponse myResponse = myRequest.GetResponse();

From the response you get a ResponseStream. For a text file you can use a
StreamReader

StreamReader sr = new StreamReader(myResponse.GetResponseStream()); //
using UTF8 encoding
string text = sr.ReadToEnd();

Console.WriteLine(sr.ReadToEnd());


Even simpler is using a WebClient.DownloadFile/DownloadData, but if you
need more control, use WebRequest, or HttpWebRequest.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top