Thursday, June 26, 2014

How to write the text file using the WPF application



Introduction

This article goes to understanding of the code of writing the text file from the c# .
Here the “ExceptionHandler” will takes the input parameter as string to what the data to write in the text file
This method “CallExceptionHandler” will work for writing the test in the file
Note:-Make Shure to Create one folder in the c drive with the name of “Log”

public void ExceptionHandler(string ExceptionMessage)
        {
            try
            {
                // string root = Directory.GetCurrentDirectory() + "\\Log";
                // if (!Directory.Exists(root))
                // {
                // Directory.CreateDirectory(root);
                // }

                string root = "C:\\Log\\";
                string path = root + "SampleTextFile" + System.DateTime.Now.ToString("ddMMyyy") + ".txt";

                CallExceptionHandler(path, ExceptionMessage);

            }
            catch (Exception)
            { }
        }
 private void CallExceptionHandler(string strPath, string strException)
        {
            FileStream fsFile = null;
            StreamWriter swWriter = null;
            try
            {
                if (File.Exists(strPath))
                {
                    fsFile = new FileStream(strPath, FileMode.Append, FileAccess.Write);
                    swWriter = new StreamWriter(fsFile);
                    swWriter.WriteLine(Environment.NewLine + DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss") + "-----------" + Environment.NewLine);

                    swWriter.WriteLine(strException);
                }
                else
                {
                    fsFile = new FileStream(strPath, FileMode.Create, FileAccess.Write);
                    swWriter = new StreamWriter(fsFile);
                    swWriter.WriteLine(strException);
                }
                swWriter.Flush();

            }
            catch (Exception)
            {
            }
            finally
            {
                swWriter.Close(); fsFile.Close(); swWriter.Dispose(); fsFile.Dispose();
            }
        }


No comments:

Post a Comment