尝试通过写入本地日志文件来调试c#webmethod - 日志文件为空

时间:2014-10-22 15:22:56

标签: c# asp.net webmethod

这是我背后的代码。如您所见,我试图通过写入我的机器上的本地文件来处理变量值。出于某种原因,文件中没有任何内容。所有的建议都表示赞赏,提前谢谢。

[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static bool GetEdits(string PMID, string Drug, string Gene, string SNP)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\istrauss\Desktop\Log.txt");
            DeveloprodDataClassDataContext masterDB = new DeveloprodDataClassDataContext();
            bool alreadyInDB = false;

            file.WriteLine("PMID: " + PMID + ", Drug: " + Drug + ", Gene: " + Gene + ", SNP: " + SNP);

//Other stuff

        return alreadyInDB;
    }

2 个答案:

答案 0 :(得分:1)

System.IO.StreamWriter实现了IDisposable,因此您应该在using语句中使用它。您可能还需要致电Flush

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static bool GetEdits(string PMID, string Drug, string Gene, string SNP)
        {
            bool alreadyInDB = false;

            using(System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\istrauss\Desktop\Log.txt"))
            {
                DeveloprodDataClassDataContext masterDB = new DeveloprodDataClassDataContext();

                file.WriteLine("PMID: " + PMID + ", Drug: " + Drug + ", Gene: " + Gene + ", SNP: " + SNP);

                //Other stuff

                file.Flush();
            }    

            return alreadyInDB;
        }

答案 1 :(得分:0)

如果file.Flush()

,您需要file.Close(),然后才能更好地离开
using(System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\istrauss\Desktop\Log.txt")){
            DeveloprodDataClassDataContext masterDB = new DeveloprodDataClassDataContext();
            bool alreadyInDB = false;

            file.WriteLine("PMID: " + PMID + ", Drug: " + Drug + ", Gene: " + Gene + ", SNP: " + SNP);

    file.Flush();
    file.Close();
}

如果您使用上面示例中使用的using关键字来确保资源在使用完毕后保证正确免费,那么效果会更好。

相关问题