Byc
Byc

Reputation: 183

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

Upvotes: 1

Views: 819

Answers (2)

Dalorzo
Dalorzo

Reputation: 20014

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.

Upvotes: 0

Tobsey
Tobsey

Reputation: 3400

System.IO.StreamWriter implements IDisposable so you should use it within a using statement. Also you probably need to call 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;
        }

Upvotes: 1

Related Questions