Search code examples
c#debuggingsilverlightsilverlight-5.0trace

How to use Trace in Silverlight client?


How do I use Trace class to store tracing info in a file in a Silverlight client code? In server side code I change config to have tracing info directed into a file. What should I do to make tracing written to a file on the client side?

I dont use Application Blocks and I want use Trace.WriteLine.


Solution

  • As you may know, Silverlight is running in the "almighty" sandbox. Due to this, you won't have direct file access. To solve this problem, you can write a file into the isolated storage of your application.

    Side note: As far as I know, Trace.WriteLine doesn't exist in Silverlight?

    To do so, write a class that represents your Trace, and implements a WriteLine method:

    public static class SilverlightTrace
    {
        public static void WriteLine(string message)
        {
            try
            {
                if (IsolatedStorageFile.IsEnabled)
                {
                    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        // Create trace file, if it doesn't exist
                        if(!store.FileExists("YourFileName.txt"))
                        {
                            var stream = store.CreateFile("YourFileName.txt");
                            stream.Close();
                        }
    
                        using (var writer = new StreamWriter(
                                            store.OpenFile("YourFileName.txt",
                                                           FileMode.Append,
                                                           FileAccess.Write)))
                        {
                            writer.WriteLine(message);
                            writer.Close();
                        }
                    }
                }      
            }
            catch(Exception e)
            {
                // Add some error handling here
            }
        }
    }