Search code examples
c#visual-studiofilewritertxt

Event Trigger Not Writing to .txt File in Resource Folder - Issue Resolved


I encountered an issue with an event trigger that was supposed to write to a .txt file within my resource folder. However, no data was being written to the designated folder. After some investigation, I realized that the code was functioning correctly, but the .txt file was being created in the debug folder, not the resource folder as I initially assumed.

Here's the original code snippet:

private void button1_Click(object sender, EventArgs e)
{
    int b = numericUpDown1.GetHashCode();
    int c = numericUpDown2.GetHashCode();
    int d = numericUpDown3.GetHashCode();

    try
    {
        StreamWriter sw = new StreamWriter("orders.txt");
        sw.WriteLine("Burger(s) " + b);
        sw.WriteLine("Chip(s): " + c);
        sw.WriteLine("Drink(s) " + d);
        sw.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception: " + ex.Message);
    }
}

Update:

Upon further inspection, I realized the .txt file was being created in the debug folder, not the resource folder. This oversight led to confusion regarding why the data wasn't being written as expected.

I appreciate the assistance provided, and I've marked this issue as resolved. Thank you!


Solution

  • You can use this method:

    class WriteAllLines
    {
      public static async Task ExampleAsync()
    {
        string[] lines =
        {
            "First line", "Second line", "Third line" 
        };
    
        await File.WriteAllLinesAsync("WriteLines.txt", lines);
    }
    

    }

    from microsoft

    Here