【问题标题】:Writing a file by a webservice通过 Web 服务写入文件
【发布时间】:2010-06-12 19:57:34
【问题描述】:

我有一个 wevservice,我想将日志写入文本文件。

我的问题是我不知道创建streamwriter时要给出什么路径:

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

你能帮我输入什么路径吗?

【问题讨论】:

  • 你想在哪里创建文本文件?
  • 最好在asmx文件的同一位置

标签: .net web-services path asmx streamwriter


【解决方案1】:

不管你把它放在哪里,你只需要给网络服务适当的权限到你想写的位置。您可以查看应用程序池以了解您需要授予哪个用户权限,或者您可以使用模拟。

如果您使用"MyLogfile.log",它将位于与 Web 服务相同的位置,因此相对路径将使其相对于该位置。但是,您也可以使用绝对路径,例如 "c:/log/MyLogfile.log"。

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    Server.MapPaththis article on Codeproject

    更新:这里的示例是为了在服务器上部署并为日志文件创建一个子目录。您可以使用浏览器进行测试。

    <%@ 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();
        }
    }
    

    【讨论】:

    • MapPath 将 Web 服务器上的虚拟路径转换为您需要的物理路径作为 StreamWriter 的参数所以整个物理路径应该是 Path.Combine(Server.MapPath("/myvirtualdir"), "logfile.txt");
    • 我不认为这在 web 服务中工作......我收到一个错误,该方法在当前上下文中不存在。
    • 我指的是"MapPath" in (Path.Combine(Microsoft.SqlServer.Server.MapPath("/myvirtualdir"), "logfile.txt");
    • 我指的是 System.Web 命名空间。 SQL Server 与它无关
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多