Wednesday, June 20, 2012

asp.net c# write to txt file


string path = HttpContext.Current.Server.MapPath("~/xxxxxxxx.txt");
                if (!System.IO.File.Exists(path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = System.IO.File.CreateText(path))
                    {
                        sw.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------");
                        sw.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------");
                        sw.WriteLine("------------------------Some explanation of the purpose of this file-----------------------------");
                        sw.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------");
                        sw.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------");
                    }
                }
                using (StreamWriter sw = System.IO.File.AppendText(path))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
                    sb.AppendLine("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
                    sb.AppendLine("WHEN: " + DateTime.Now.ToString());
                    sb.AppendLine("WHO: " + GetCurrentUser());
                    IPHostEntry host;
                    host = Dns.GetHostEntry(Dns.GetHostName());
                    foreach (IPAddress ip in host.AddressList)
                    {
                        if (ip.AddressFamily.ToString() == "InterNetwork")
                        {
                            sb.AppendLine("WHERE: " + ip.ToString());
                            break;
                        }
                    }
                    sb.AppendLine("WHAT: " + errorMsg);
                    sb.AppendLine();
                    sb.AppendLine();
                    sb.AppendLine();
                    sw.WriteLine(sb.ToString());
                }


No comments: