Search code examples
c#asp.netwebmethod

Trying to debug c# webmethod by writing to local log file - Log file is empty


Here is my code behind. As you can see, I am trying to get a handle on what variable values by writing to a local file on my machine. For some reason, there is nothing in the file. All advice is appreciated, thanks in advance.

[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;
    }

Solution

  • You need to file.Flush() and then before you leave better if you 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();
    }
    

    Also better is if you use using keyword like used in the sample above to guarantee that resources are properly free after you are done using them.