无法从字符串转换为system.io.stream [英] Cannot convert from string to system.io.stream

查看:109
本文介绍了无法从字符串转换为system.io.stream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在第366行,我收到错误无法从字符串转换为System.IO.Stream。



和第383行,我正在获取streamwriter不包含关闭的定义。









On line 366 , i am getting error cannot convert from string to System.IO.Stream.

and on line 383, i am getting streamwriter does not contain a definition for close.




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);

            this.display();

        }


        // displays the database

        public void display()
        {

            // a is the number of rows 
            int a = -1;

            a = this.Countrows();

            //Console.WriteLine(a);


            // b is the number of columns
            int b = this.Countcolumns();

            //Console.WriteLine(b);


            //create a new list with 3 columns , b = 3; b is the number of columns 
            List<string>[] newlist = new List<string>[b];


            // this.Select() fetches the dataset, set it to equal to newlist 
            newlist = this.Select();


            Console.WriteLine("Id" + " " + "username" + " " + "password");

            for (int j = 0; j < a; j++) // iterate through each row; a is total number of rows 
            {


                for (int i = 0; i < b; i++) // ITERATE THROUGH EACH COLUMN  ; b is total number of columns
                {
                    Console.Write(newlist[i][j] + " ");


                }
                // for each  row of obsv..write a new line
                Console.WriteLine();
            }


        }


        //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 of 3 elements to store the result
            List<string>[] list = new List<string>[3];


            // each element of list is a new list of strings
            list[0] = new List<string>();
            list[1] = new List<string>();
            list[2] = new List<string>();

            //Open connection, running OpenConnection() will open the 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        
                // iterate through each row... dataReader.Read will get the data for each row...
                while (dataReader.Read())
                {

                    // iterate through each column, add the id , username, password list[0] is column1 which is id, list[1] IS COLUMN2 WHICH IS USERNAME... list[0][0]  element column 1 , row 1 

                    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 Countrows()
        {
            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;
            }

        }




        public int Countcolumns()
        {

            string query = "SELECT Count(*) FROM INFORMATION_SCHEMA.COLUMNS  WHERE table_schema = 'first_db'  AND table_name = '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!");

                Console.WriteLine("ex.message");
            }



        }



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



}





我尝试过:



我不知道该放什么。这只是一个我没有概念的错误。因为我对C#完全不熟悉,所以我在这里谅解。



What I have tried:

I am not sure what to put here. this is just an error which i have no concept of. as i am completely new to C# , i beg your understanding here.

推荐答案

哦,你的对象错了,你写的是

Oh you got the objects wrong, what you wrote was
string path = "C:\\MySqlBackup" + year + "-" + month + "-" + day +
           "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
               StreamWriter file = new StreamWriter(path);







但你想做的是在制作作家之前创建流,并记住要么逃避转义字符(反斜杠)或使用编译时常量指示符(@)






But what you want to do is to create the stream before making the writer, and remember to either escape your escape characters (backslash) or use compiletime constant indicator (@)

string path = @"C:\\MySqlBackup" + year + "-" + month + "-" + day +
                           "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                var writer = new StreamWriter(stream, Encoding.UTF8);
                writer.Write("Hello world");
                writer.Flush();
                writer.Close();
            }


这篇关于无法从字符串转换为system.io.stream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆