@manhnguyenv

Welcome to my blog!

Write to a Text File

November 25, 2018 22:27

Write to a Text File in C# (edit)

Usage

MyLogger.WriteLine("\r\nSET DATEFORMAT DMY;\r\n" + sQuery);

On the fly

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

public bool HasPermission(string permissionKey)
{
    string strDesktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
    string strDebugTxtPath = System.IO.Path.Combine(strDesktopPath, "Debug.txt");
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(strDebugTxtPath, true))
    {
        if (!string.IsNullOrWhiteSpace(permissionKey)) file.WriteLine(permissionKey);
    }
}

Code base

public static class MyLogger
{
    private static string M_LogFilePath = "";

    static MyLogger()
    {
        M_LogFilePath = Path.Combine(Application.StartupPath, "SQL.log");

        if (!File.Exists(M_LogFilePath))
        {
            using (StreamWriter writer = new StreamWriter(M_LogFilePath, true))
            {
                writer.WriteLine($"Start Debug at: {DateTime.Now.ToString("yyyy-MM-dd HH:mm tt")}");
            }
        }
    }

    public static void AppendLine(string line)
    {
        using (StreamWriter streamWriter = File.AppendText(M_LogFilePath))
        {
            streamWriter.WriteLine(line);
        }
    }

    public static void WriteLine(string line)
    {
        using (StreamWriter streamWriter = new StreamWriter(M_LogFilePath, true))
        {
            streamWriter.WriteLine(line);
        }
    }
}

Categories

Recent posts