1

i am writing a web method to return an html file to android client here is the code i have tried

 [WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]



public class Service1 : System.Web.Services.WebService

{

[WebMethod]
public string HelloWorld()
{

    string file = Server.MapPath("index.html");
    return file;

}
}

and defiantly its not working, i am not sure about the return type of the method, which to choose. do i need to convert that html file to string and then return it to client?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
AddyProg
  • 2,960
  • 13
  • 59
  • 110
  • Are you trying to return the *contents* of the file, or the *URL* of the file? – David Mar 19 '14 at 12:21
  • i need to download the whole html file to the client, which is an android device. – AddyProg Mar 19 '14 at 12:22
  • ASMX is a legacy technology, and should not be used for new development. WCF or ASP.NET Web API should be used for all new development of web service clients and servers. One hint: Microsoft has retired the [ASMX Forum](http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/threads) on MSDN. – John Saunders Mar 19 '14 at 13:31

1 Answers1

3

Your initial post returns without doing anything else at the first line:

return "Hello World";

Remove this line if you want the rest of it to work.

In order to return the contents of the file, just do a File.ReadAll:

string filePath = Server.MapPath("index.html");
string content=File.ReadAll(filePath);
return content;

EDIT:

In order to send a file to the client, you need to send the file's bytes AND set the proper headers. This has already been answered here. You need to set the content type, content disposition and content length headers. You need to write something like this:

var fileBytes=File.ReadAllBytes(filePath);

Response.Clear();
Response.ClearHeaders();
Response.ContentType = "text/html; charset=UTF-8";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filePath + "\"");
Response.AddHeader("Content-Length", fileBytes.Length);
Response.OutputStream.Write(fileBytes, 0, fileBytes.Length);
Response.Flush();
Response.End();

Just calling Response.WriteFile isn't enough because you need to set the proper headers

Community
  • 1
  • 1
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • thanks for reply, but what if i want to return the whole file , not the contents of file ? – AddyProg Mar 19 '14 at 12:29
  • That was answered [here](http://stackoverflow.com/questions/2239623/download-file-from-webservice-in-asp-net-site). You need to return a byte array setting the proper headers, so the client will understand you are sending a file as an attachment – Panagiotis Kanavos Mar 19 '14 at 12:52