Search code examples
c#mysqltextstreamwriterexecutereader

MySql to .txt in C# WPF


I am trying to get a table from my local database to download into a .txt. I've and I'm honestly at a loss.

It has to be in a txt for simplicity of other users. I've tried a few different ways, I've tried to call it as if I was writing it to a datagrid, which didn't work.

I am getting results from the Reader @

while (dbReader.Read())
                {
                    MessageBox.Show(dbReader.GetValue(0).ToString());
                }

So it is pulling and reading the information, it's just not writing it to a txt file. Here's the code.

 private void btnDLSql_Click(object sender, RoutedEventArgs e)
        {
            string dbConnection = "datasource=127.0.0.1;port=3306;username=root;password=12345";
            MySqlConnection conDataBase = new MySqlConnection(dbConnection);
            MySqlCommand SelectCommand = new MySqlCommand("select GUID,BanTime,Reason from bans.bans order by BanType asc", conDataBase);

            conDataBase.Open();

            MySqlCommand command = conDataBase.CreateCommand();
            MySqlDataReader dbReader = SelectCommand.ExecuteReader();

            if (dbReader != null)
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\mccla\Desktop\A3Bans.txt", true);

                while (dbReader.Read())
                {
                    MessageBox.Show(dbReader.GetValue(0).ToString());
                }
            }

            conDataBase.Close();

        }

Any help would be greatly appreciated. Sorry for the questions, I usually try and figure stuff out on my own. But just can't find any information for this.


Solution

  • You currently aren't writing to your file or closing it when you are done. You should also be using using statements, as mentioned by SLaks in the comments.

    You could probably simplify your code to:

            var dbConnection = "datasource=127.0.0.1;port=3306;username=root;password=12345";
            using (var conDataBase = new MySqlConnection(dbConnection))
            using (var selectCommand = new MySqlCommand("select GUID,BanTime,Reason from bans.bans order by BanType asc", conDataBase)) {
                var dbReader = selectCommand.ExecuteReader();
                using (var file = new System.IO.StreamWriter(@"C:\Users\mccla\Desktop\A3Bans.txt", true)) {
                    while (dbReader.Read()) {
                        file.Write(dbReader.GetValue(0).ToString());
                    }
                }
            }