C#FTP上传困难

时间:2016-04-14 15:23:04

标签: c# visual-studio ftp

我正在开发一个UI,允许用户在本地更新数据库,然后将其发布到服务器。当用户点击发布按钮时,应将本地文件(bk.db)上载到服务器,并将文本添加到日志文件中。它似乎按预期写入日志文件;但是,.db文件(在服务器上,而不是本地)总是以0字节结尾(基本上它没有正确复制文件)。问题可能是什么?

主要班级:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Data;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Forms;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.IO;
using System.Data.SQLite;
using System.Drawing;

namespace Burger_King_Database
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window


    {
        private SQLiteConnection con;
        private OpenFileDialog thumbDialog = new OpenFileDialog();
        private OpenFileDialog fullDialog = new OpenFileDialog();
        private System.Drawing.Image iconImage;
        private System.Drawing.Image buildImage;
        private string itemName;
        private int itemLocation;
        private int lto;
        private ftp uploader = new ftp("host", "user", "pass");


        public MainWindow()
        {
            InitializeComponent();
            connect();
        }

        private void connect()
        {
            try
            {

                con = new SQLiteConnection("Data Source=Z:\\bk.db;Pooling=true;FailIfMissing=false");


                con.Open();
            }
            catch (SQLiteException e)
            {
                System.Windows.MessageBox.Show("Error: " + e.Message);
            }

        }

        public byte[] ConvertImgToArray(System.Drawing.Image image, System.Drawing.Imaging.ImageFormat format) {
            byte[] result;
            try {
                using(MemoryStream m = new MemoryStream()) {
                    image.Save(m, format);
                    result = m.ToArray();

                }
                return result;
            }
            catch (Exception e) {
                    System.Windows.MessageBox.Show("Error: " + e);
                }
            return null;
        }
        private void adminWindow_Loaded(object sender, RoutedEventArgs e)
        {


            locationBox.Items.Add("Breakfast");
            locationBox.Items.Add("Main Boards");
            locationBox.Items.Add("Speciality");

            thumbDialog.InitialDirectory = "c:\\";
            thumbDialog.Filter = "Image Files | *.jpg";
            thumbDialog.RestoreDirectory = true;

            fullDialog.InitialDirectory = "c:\\";
            fullDialog.Filter = "Image Files | *.jpg";
            fullDialog.RestoreDirectory = true;
        }

        private void thumbImageButton_Click(object sender, RoutedEventArgs e)
        {

            if (thumbDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {

                    thumb.Content = thumbDialog.FileName;
                    iconImage = System.Drawing.Image.FromFile(thumbDialog.FileName);

                }
                catch (Exception er)
                {
                    System.Windows.MessageBox.Show("Error: " + er);
                }
            } 
        }



        private void fullImageButton_Click(object sender, RoutedEventArgs e)
        {

            if (fullDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    build.Content = fullDialog.FileName;
                    buildImage = System.Drawing.Image.FromFile(fullDialog.FileName);

                }
                catch (Exception er)
                {
                    System.Windows.MessageBox.Show("Error: " + er);
                }
            }
        }

        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            bool valid = true;
            string errorMessage = "Please correct the following errors: \n";
            if((bool)ltoNo.IsChecked) {
                lto = 0;
            } else if ((bool)ltoYes.IsChecked) {
                lto = 1;
            }           
                else {valid = false;
                errorMessage += "LTO option must be selected!\n";
                }


            if(locationBox.SelectedIndex != -1) {
               itemLocation = locationBox.SelectedIndex + 1;
            } else {
                valid = false;
                errorMessage += "Please select a location!\n";
            }

            if(nameBox.Text != "") {
                itemName = nameBox.Text;
            } else { 
                valid = false;
                errorMessage += "Please enter a name for the item!\n";
            }

            if(iconImage == null || buildImage == null) {
                valid = false;
                errorMessage += "Please selected both a thumbnail and fullsize image!";
            }

            if(valid) {
            byte[] iconImageBytes = ConvertImgToArray(iconImage, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] buildImageBytes = ConvertImgToArray(buildImage, System.Drawing.Imaging.ImageFormat.Jpeg);





            SQLiteCommand sql = new SQLiteCommand("INSERT INTO items (name, location, lto, icon, buildImage) values (@name, @location, @lto, @icon, @buildImage)", con);

            sql.Parameters.Add("@name", DbType.String);
            sql.Parameters.Add("@location", DbType.Int16);
            sql.Parameters.Add("@lto", DbType.Int16);
            sql.Parameters.Add("@icon", DbType.Binary);
            sql.Parameters.Add("@buildImage", DbType.Binary);
            sql.Parameters["@name"].Value = itemName;
            sql.Parameters["@location"].Value = itemLocation;
            sql.Parameters["@lto"].Value = lto;
            sql.Parameters["@icon"].Value = iconImageBytes;
            sql.Parameters["@buildImage"].Value = buildImageBytes;
            sql.ExecuteNonQuery();

            System.Windows.MessageBox.Show("Inserted: " + itemName);


                // reset form

                ltoNo.IsChecked = false;
                ltoYes.IsChecked = false;
                build.Content ="Select a Full Size Image:";
                thumb.Content = "Select a Thumbnail Image";
                nameBox.Text = "";
                locationBox.SelectedIndex = -1;
            }
         else {System.Windows.MessageBox.Show(errorMessage);}
        }

        private void adminWindow_Closed(object sender, EventArgs e)
        {
            con.Close();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DateTime now = DateTime.Now;
            string updateText = "updated," + now + "\n";
              uploader.uploadFile("Z:\\bk.db", "bk.db");
              uploader.appendFile(updateText, "update.txt");
                   System.Windows.MessageBox.Show("Changes published to server");
        }
        }
    }

和ftp类

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

namespace Burger_King_Database
{
    class ftp
    {
        private string host;
        private string user;
        private string pass;
        private FtpWebRequest request = null;
        private Stream stream = null;

        public ftp(string hostString, string userName, string password) {
            this.host = hostString;
            this.user = userName;
                this.pass = password;
    }


        public void uploadFile(string local, string remote)
        {
            try
            {
                request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + remote);
                request.Credentials = new NetworkCredential(user, pass);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.KeepAlive = true;
                stream = request.GetRequestStream();
                FileStream localStream = new FileStream(local, FileMode.Open);

                byte[] buffer = new byte[1024];

                int read = localStream.Read(buffer, 0, 1024);

                try
                {
                    while (read != 0)
                    {
                        stream.Write(buffer, 0, read);
                        read = localStream.Read(buffer, 0, 1024);
                    }
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
                stream.Close();
                localStream.Close();
                request = null;

            }
            catch (Exception e) { Console.WriteLine(e.Message); }
            return;

        }

        public void appendFile(string appendText, string remoteFile)
        {
            try
            {
                request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + remoteFile);
                request.Credentials = new NetworkCredential(user, pass);
                request.KeepAlive = true;

                request.Method = WebRequestMethods.Ftp.AppendFile;
                stream = request.GetRequestStream();

                byte[] text = Encoding.ASCII.GetBytes(appendText);

                stream.Write(text, 0, text.Length);

                stream.Close();
                request = null;

            }
            catch (Exception e) { Console.WriteLine(e.Message); }
        } 
    }
}

0 个答案:

没有答案