views:

39

answers:

2

Hi,

I have a wevservice, and I would like to write logs into a textfile.

My problem is that i do not know what path to give when creating the streamwriter:

TextWriter tw = new StreamWriter("????");

Can you please help what path I should enter?

+1  A: 

see Server.MapPath also this article on Codeproject

EDIT: Full example is in order Deploy on server and create a subdirectory for log files. Test using your browser.

<%@ WebService Language="c#" Class="Soap"%>
    using System;
    using System.Data;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.IO;

    [WebService]
    public class Soap : System.Web.Services.WebService
    {
        [WebMethod(EnableSession=true)]
        public bool Login(string userName, string password)
        {
            //NOTE: There are better ways of doing authentication. This is just illustrates Session usage.
            LogText("Login User = " + userName);
            UserName = userName;
            return true;
        }

        [WebMethod(EnableSession=true)]
        public void Logout()
        {    
            LogText("Logout User = " + UserName);
            Context.Session.Abandon();
        }

        private string UserName {
            get {return (string)Context.Session["User"];}
            set {Context.Session["User"] = value;}
        }

        private void LogText(string s) {
            string fname = Path.Combine(
                Server.MapPath( "/logs" ), "logfile.txt");
            TextWriter tw = new StreamWriter(fname);
            tw.Write("Yada yada :" + s);
            tw.Close();
        }
    }
renick
thanks but where I should add this??
mouthpiec
MapPath converts a virtual path on the web server to a physical path that you need as an argument to StreamWriter So the whole physical path should be Path.Combine(Server.MapPath("/myvirtualdir"), "logfile.txt");
renick
i do not think that this work in a webservice .... I am getting an error that the method do not exist in the current context.
mouthpiec
I am referring to "MapPath" in ( Path.Combine(Microsoft.SqlServer.Server.MapPath("/myvirtualdir"), "logfile.txt");
mouthpiec
I am referring to the System.Web namespace. SQL Server has nothing to do with it
renick
+2  A: 

It doesn't matter where you put it, you just need to give the web service the appropriate permissions to the location you want to write to. You can take a look at the Application pool to see which user you need to give the permissions, or you can use impersonation.

If you use "MyLogfile.log" it will be located in the same location as the web service, so a relative path will put it relative to that location. You can however use a absolute path too, like "c:/log/MyLogfile.log".

I hope it helped.

Arkain