Click here to Skip to main content
15,903,362 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am following the tutorial by Connect C# to MySQL[^]


For some reason when i run the Backup() method , i am getting this error: and i try to look for the file but it is not there.


C#
<pre lang="C#">An unhandled exception of type &#39;System.UnauthorizedAccessException&#39; occurred in mscorlib.dll

Additional information: Access to the path &#39;C:\MySqlBackup2016-11-4-8-23-4-270.sql&#39; is denied.</pre>






using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using MySql.Data.MySqlClient;

using System.Diagnostics;


using System.IO;



namespace connect
{

    class DBConnect
    {
        private MySqlConnection connection;
        private string server;
        private string database;
        private string uid;
        private string password;

        //Constructor
        public DBConnect()
        {
            Initialize();
        }

        //Initialize values
        private void Initialize()
        {
            server = "localhost";
            database = "first_db";
            uid = "root";
            password = "";
            string connectionString;
            connectionString = "SERVER=" + server + ";" + "DATABASE=" +
            database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

            connection = new MySqlConnection(connectionString);
        }

        //open connection to database
        public bool OpenConnection()
        {

            try
            {
                connection.Open();

                Console.WriteLine("connection opened");

                return true;
            }
            catch (MySqlException ex)
            {
                //When handling errors, you can your application's response based 
                //on the error number.
                //The two most common error numbers when connecting are as follows:
                //0: Cannot connect to server.
                //1045: Invalid user name and/or password.
                switch (ex.Number)
                {
                    case 0:
                        Console.WriteLine("Cannot connect to server.  Contact administrator");
                        break;

                    case 1045:
                        Console.WriteLine("Invalid username/password, please try again");
                        break;
                }
                return false;
            }



        }

        //Close connection
        public bool CloseConnection()
        {
            try
            {
                connection.Close();

                Console.WriteLine("connection closed");
                return true;
            }
            catch (MySqlException ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }



        }
        


        //Insert statement
        public void Insert()
        {

            string query = "INSERT INTO users (id, username, password) VALUES('23' ,'Jojo', '33')  , ('99', 'jen', '66')";

    //open connection
    if (this.OpenConnection() == true)
    {
        //create command and assign the query and connection from the constructor
        MySqlCommand cmd = new MySqlCommand(query, connection);

        Console.WriteLine("values inserted");


        
        //Execute command
        cmd.ExecuteNonQuery();

        //close connection
        this.CloseConnection();
    }

        }



        

        //Update statement
        public void Update()
        {

          string query = "UPDATE users SET username='Joe', password='22', id='33'  WHERE username='Joe'";

    //Open connection
    if (OpenConnection() == true)
    {
        //create mysql command
        MySqlCommand cmd = new MySqlCommand();
        //Assign the query using CommandText
        cmd.CommandText = query;
        //Assign the connection using Connection
        cmd.Connection = connection;

        //Execute query
        cmd.ExecuteNonQuery();

        //close connection
        this.CloseConnection();
    }



        }



        
        //Delete statement
        public void Delete()
        {

            string query = "DELETE FROM users WHERE username='Joe'";

            if (this.OpenConnection() == true)
            {
                MySqlCommand cmd = new MySqlCommand(query, connection);
                cmd.ExecuteNonQuery();
                this.CloseConnection();
            }


        }


       
        //Select statement
        public List<string>[] Select()
        {
            string query = "SELECT * FROM users";

    //Create a list to store the result
    List< string >[] list = new List< string >[3];
    list[0] = new List< string >();
    list[1] = new List< string >();
    list[2] = new List< string >();

    //Open connection
    if (this.OpenConnection() == true)
    {
        //Create Command
        MySqlCommand cmd = new MySqlCommand(query, connection);
        //Create a data reader and Execute the command
        MySqlDataReader dataReader = cmd.ExecuteReader();
        
        //Read the data and store them in the list
        while (dataReader.Read())
        {
            list[0].Add(dataReader["id"] + "");
            list[1].Add(dataReader["username"] + "");
            list[2].Add(dataReader["password"] + "");
        }

        //close Data Reader
        dataReader.Close();

        //close Connection
        this.CloseConnection();

        //return list to be displayed
        return list;
    }
    else
    {
        return list;
    }

        }



        //Count statement
        public int Count()
        {
             string query = "SELECT Count(*) FROM users";
    int Count = -1;

    //Open Connection
    if (this.OpenConnection() == true)
    {
        //Create Mysql Command
        MySqlCommand cmd = new MySqlCommand(query, connection);

        //ExecuteScalar will return one value
        Count = int.Parse(cmd.ExecuteScalar()+"");
        
        //close Connection
        this.CloseConnection();

        return Count;
    }
    else
    {
        return Count;
    }

        }



        //Backup
        public void Backup()
        {
             try
    {
        DateTime Time = DateTime.Now;
        int year = Time.Year;
        int month = Time.Month;
        int day = Time.Day;
        int hour = Time.Hour;
        int minute = Time.Minute;
        int second = Time.Second;
        int millisecond = Time.Millisecond;

        //Save file to C:\ with the current date as a filename
        string path;
        path = "C:\\MySqlBackup" + year + "-" + month + "-" + day + 
	"-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
        StreamWriter file = new StreamWriter(path);

        
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "mysqldump";
        psi.RedirectStandardInput = false;
        psi.RedirectStandardOutput = true;
        psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", 
			uid, password, server, database);
        psi.UseShellExecute = false;

        Process process = Process.Start(psi);

        string output;
        output = process.StandardOutput.ReadToEnd();
        file.WriteLine(output);
        process.WaitForExit();
        file.Close();
        process.Close();
    }
    catch (IOException ex)
    {
        Console.WriteLine("Error , unable to backup!");
    }



        }



        /*
        //Restore
        public void Restore()
        {
        }
         * 
          */
    }






}


What I have tried:

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Posted
Updated 3-Nov-16 21:10pm
Comments
[no name] 3-Nov-16 21:09pm    
"Access denied" is pretty self explanatory.
Philippe Mori 3-Nov-16 22:59pm    
Read the message then verify if you can access the file and if not why...
Karthik_Mahalingam 4-Nov-16 11:01am    
post only the relevant code block

1 solution

Look at the error:
Access to the path 'C:\MySqlBackup2016-11-4-8-23-4-270.sql' is denied

It's pretty clear! The folder you are asking MySql to output to does not have write permissions for the user that MySql uses to dump it's data: change the permissions on the folder so that all users can create, delete, read, and write files in the folder.

But please, don't put your path in a hardcoded string: use a configuration file or an application parameter to pass it instead.
And don't store your backups directly in the root folder: set up a folder off the root and create subfolders under that - it's not a good idea to clutter the root, or routinely change anything in it unless it's absolutely necessary.
 
Share this answer
 
Comments
forte74 6-Nov-16 3:02am    
but i can't even find the file...how do i change the write permissions
OriginalGriff 6-Nov-16 4:11am    
If you can't find the file, it's because the access permissions didn't permit anyone to write it!
Seriously, don't store files in the root: access there is severely restricted, for good reasons - particularly if it's your boot drive.
forte74 6-Nov-16 5:18am    
how do i change the write permissions
OriginalGriff 6-Nov-16 5:29am    
On the root directory of a boot drive, you probably can't - and certainly shouldn't, unless you like viruses - On other directories, its simple:
In Windows Explorer, right click the folder, and select "Properties"
Select the "Security" tab, and highlight the user group you are interested in.
Press the "Edit..." button, and it's pretty obvious from there.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900