Remoting 实例

本文介绍了一种视频备份系统,该系统通过客户端与服务器交互实现视频文件的定期备份与记录。客户端每五分钟向服务器发送备份请求,服务器接收并处理请求后,将备份路径存入SQL Server数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本项目用来备份视频文件。

视频文件生成后会存储在一台存储空间为5t多的机器上。为了避免数据损失,将5t上的部分新的文件存储在一台存储空间为2.5t多的机器上。本软件就是用来复制数据和记录数据的。

其中,server运行于2.5t的机器,client运行于5t机器。

server主要用于监听客户端的请求并且给与相应。

client用于发送请求。

本软件的机制:客户端每五分钟发送一个备份请求给服务器,并在服务器相应完成后,将存储路径存在sqlserver数据库中。

[VideoBack.VideoBackCommon.VBFileController.cs]

using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Diagnostics;

namespace VideoBack.VideoBackCommon
{
    /// <summary>
    /// 该类用于对文件进行相关操作。
    /// </summary>
    public class VBFileController
    {
        /// <summary>
        /// 用于创建指定的文件夹。
        /// 返回:True:创建成功,false:创建失败。
        /// </summary>
        /// <param name="fullPath">目标文件夹的完整路径。</param>
        /// <returns>返回:True:创建成功,false:创建失败。</returns>
        public static bool DirectoryCreate(string fullPath)
        {
            try
            {
                Directory.CreateDirectory(fullPath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于删除指定的文件夹。
        /// 返回:True:删除成功,false:删除失败。
        /// </summary>
        /// <param name="fullPath">目标文件夹的完整路径。</param>
        /// <returns>返回:True:删除成功,false:删除失败。</returns>
        public static bool DirectoryDelete(string fullPath)
        {
            try
            {
                Directory.Delete(fullPath, true);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于判断指定的文件夹是否存在。
        /// 返回:True:文件夹存在,false:文件夹不存在。
        /// </summary>
        /// <param name="fullPath">目标文件夹的完整路径。</param>
        /// <returns>返回:True:文件夹存在,false:文件夹不存在。</returns>
        public static bool DirectoryExists(string fullPath)
        {
            try
            {
                return Directory.Exists(fullPath);
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 用于判断指定的文件夹中是否有文件存在
        /// 返回:true:文件夹中存在文件,false:文件夹中不存在文件
        /// </summary>
        /// <param name="fullPath">目标文件夹的完整路径</param>
        /// <returns>返回:true:文件夹中存在文件,false:文件夹中不存在文件</returns>
        public static bool IsHasFiles(string fullPath)
        {
            try
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(fullPath);
                FileInfo[] fileInfo = null;
                fileInfo = directoryInfo.GetFiles();
                if (fileInfo.Length == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return true;
            }
        }
        /// <summary>
        /// 用于判断指定的文件夹中是否有文件夹存在
        /// 返回:true:目标文件夹中存在文件夹,false:目标文件夹中不存在文件夹
        /// </summary>
        /// <param name="fullPath">目标文件夹的完整路径</param>
        /// <returns>返回:true:目标文件夹中存在文件夹,false:目标文件夹中不存在文件夹</returns>
        public static bool IsHasSubDirectory(string fullPath)
        {
            try
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(fullPath);
                DirectoryInfo[] directoryInfos = null;
                directoryInfos = directoryInfo.GetDirectories();
                if (directoryInfos.Length == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }

            }
            catch
            {
                return true;
            }
        }


        /// <summary>
        /// 用于移动源文件夹到指定位置,或者更改文件夹名称。
        /// 返回:Ture:操作成功,False:操作失败。
        /// </summary>
        /// <param name="sourceFullPath">源文件夹的完整路径。</param>
        /// <param name="destFullPath">目标文件夹的完整路径。</param>
        /// <returns>返回:Ture:操作成功,False:操作失败。</returns>
        public static bool DirectoryMove(string sourceFullPath, string destFullPath)
        {
            try
            {
                Directory.Move(sourceFullPath, destFullPath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于创建指定的文件。
        /// 返回:True:创建成功,false:创建失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:True:创建成功,false:创建失败。</returns>
        public static bool FileCreate(string fullPath)
        {
            try
            {
                File.Create(fullPath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于删除指定的文件。
        /// 返回:True:删除成功,false:删除失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:True:删除成功,false:删除失败。</returns>
        public static bool FileDelete(string fullPath)
        {
            try
            {
                File.Delete(fullPath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于判断指定的文件是否存在。
        /// 返回:True:文件存在,false:文件不存在。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:True:文件存在,false:文件不存在。</returns>
        public static bool FileExists(string fullPath)
        {
            try
            {
                return System.IO.File.Exists(fullPath);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于移动源文件到指定位置,或者更改文件名称。
        /// 返回:Ture:操作成功,False:操作失败。
        /// </summary>
        /// <param name="sourceFullPath">源文件的完整路径及文件名。</param>
        /// <param name="destFullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:Ture:操作成功,False:操作失败。</returns>
        public static bool FileMove(string sourceFullPath, string destFullPath)
        {
            try
            {
                File.Move(sourceFullPath, destFullPath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于按行读取指定文件。
        /// 返回:以字符串数组的形式返回文件中的所有行。null:读取失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:以字符串数组的形式返回文件中的所有行。null:读取失败。</returns>
        public static string[] ReadAllLines(string fullPath)
        {
            try
            {
                return File.ReadAllLines(fullPath, Encoding.Default);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 用于读取指定文件的所有文本。
        /// 返回:文件的所有文本。"":读取失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:文件的所有文本。"":读取失败。</returns>
        public static string ReadAllText(string fullPath)
        {
            try
            {
                return File.ReadAllText(fullPath, Encoding.Default);
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 用于以流的形式读取指定的文件。
        /// 返回:文件内容的二进制流。"":读取失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:文件内容的二进制流。"":读取失败。</returns>
        public static byte[] ReadStream(string fullPath)
        {
            byte[] buffer = null;
            FileStream fileStream = null;
            BinaryReader binaryReader = null;
            try
            {
                // 创建文件流,打开目标文件。
                fileStream = new FileStream(fullPath, FileMode.Open);
                // 以二进制读取文件流。
                binaryReader = new BinaryReader(fileStream);
                // 获得文件内容的二进制流
                buffer = new byte[binaryReader.BaseStream.Length];
                // 读取文件内容。
                binaryReader.Read(buffer, 0, buffer.Length);
            }
            finally
            {
                // 关闭对象。
                if (binaryReader != null)
                {
                    binaryReader.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }

            return buffer;
        }

        /// <summary>
        /// 用于按行写入指定文件。文件不存在时创建新文件,文件存在时覆盖旧文件内容。
        /// 返回:Ture:写入成功,False:写入失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <param name="allLine">以字符串数组的形式保存的文件中的所有行。</param>
        /// <returns>返回:Ture:写入成功,False:写入失败。</returns>
        public static bool WriteAllLines(string fullPath, string[] allLine)
        {
            try
            {
                File.WriteAllLines(fullPath, allLine, Encoding.Default);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于写入指定文件的所有文本。文件不存在时创建新文件,文件存在时覆盖旧文件内容。
        /// 返回:Ture:写入成功,False:写入失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <param name="allText">文件的所有文本。</param>
        /// <returns>返回:Ture:写入成功,False:写入失败。</returns>
        public static bool WriteAllText(string fullPath, string allText)
        {
            try
            {
                File.WriteAllText(fullPath, allText, Encoding.Default);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于写入指定XML文件的所有文本(UTF-8)。文件不存在时创建新文件,文件存在时覆盖旧文件内容。
        /// 返回:Ture:写入成功,False:写入失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <param name="allText">XML文件的所有文本。</param>
        /// <returns>返回:Ture:写入成功,False:写入失败。</returns>
        public static bool WriteAllTextForXml(string fullPath, string allText)
        {
            try
            {
                File.WriteAllText(fullPath, allText, Encoding.UTF8);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 用于以流的形式写入指定的文件。
        /// 返回:Ture:写入成功,False:写入失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <param name="fileBuffer">文件内容的二进制流。</param>
        /// <returns>返回:Ture:写入成功,False:写入失败。</returns>
        public static bool WriteStream(string fullPath, byte[] fileBuffer)
        {
            bool result = false;
            FileStream fileStream = null;
            BinaryWriter binaryWriter = null;
            try
            {
                // 创建文件流,目标文件不存在则新建。   
                fileStream = new FileStream(fullPath, FileMode.OpenOrCreate);
                // 以二进制打开文件流。
                binaryWriter = new BinaryWriter(fileStream);
                // 写文件。
                binaryWriter.Write(fileBuffer, 0, fileBuffer.Length);

                result = true;
            }
            finally
            {
                // 关闭对象。
                if (binaryWriter != null)
                {
                    binaryWriter.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }

            return result;
        }

    }
}

 

[VideoBack.VideoBackCommon.VBRemoteFileController.cs]

 

using System;
using System.Collections.Generic;
using System.Text;

namespace VideoBack.VideoBackCommon
{
    /// <summary>
    /// 该类是通过客户端Windows服务注册在客户端的共享类,
    /// 用于在服务器端对客户端的文件进行操作。
    /// </summary>
    public class VBRemoteFileController : System.MarshalByRefObject
    {
        /// <summary>
        /// 注册Remote共享类型时使用的信道。
        /// 当前值为:4022。
        /// </summary>
        public const int REMOTE_CHANNEL = 4022;
        /// <summary>
        /// 注册Remote共享类型时使用的共享名称。该类提供远程文件控制功能。
        /// 当前值为:"VBRemoteFileController"。
        /// </summary>
        public const string REMOTE_FILE_CONTROLLER_NAME = "VBRemoteFileController";

        /// <summary>
        /// 用于创建服务器指定的文件夹。
        /// 返回:True:创建成功,false:创建失败。
        /// </summary>
        /// <param name="fullPath">目标文件夹的完整路径。</param>
        /// <returns>返回:Ture:创建成功,False:创建失败。</returns>
        public bool DirectoryCreate(string fullPath)
        {
            // 创建文件夹。
            return VBFileController.DirectoryCreate(fullPath);
        }

        /// <summary>
        /// 用于删除服务器指定的文件夹。
        /// 返回:True:删除成功,false:删除失败。
        /// </summary>
        /// <param name="fullPath">目标文件夹的完整路径。</param>
        /// <returns>返回:True:删除成功,false:删除失败。</returns>
        public bool DirectoryDelete(string fullPath)
        {
            // 删除文件夹。
            return VBFileController.DirectoryDelete(fullPath);
        }

        /// <summary>
        /// 用于判断服务器指定的文件夹是否存在。
        /// 返回:True:文件夹存在,false:文件夹不存在。
        /// </summary>
        /// <param name="fullPath">目标文件夹的完整路径。</param>
        /// <returns>返回:True:文件夹存在,false:文件夹不存在。</returns>
        public bool DirectoryExists(string fullPath)
        {
            // 判断文件夹是否存在。
            return VBFileController.DirectoryExists(fullPath);
        }

        /// <summary>
        /// 用于移动源文件夹到指定位置,或者更改文件夹名称。
        /// 返回:Ture:操作成功,False:操作失败。
        /// </summary>
        /// <param name="sourceFullPath">源文件夹的完整路径。</param>
        /// <param name="destFullPath">目标文件夹的完整路径。</param>
        /// <returns>返回:Ture:操作成功,False:操作失败。</returns>
        public bool DirectoryMove(string sourceFullPath, string destFullPath)
        {
            // 删除文件夹。
            return VBFileController.DirectoryMove(sourceFullPath, destFullPath);
        }

        /// <summary>
        /// 用于创建服务器指定的文件。
        /// 返回:True:创建成功,false:创建失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:True:创建成功,false:创建失败。</returns>
        public bool FileCreate(string fullPath)
        {
            // 创建文件。
            return VBFileController.FileCreate(fullPath);
        }

        /// <summary>
        /// 用于创建服务器指定的文件。
        /// 返回:True:删除成功,false:删除失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:True:删除成功,false:删除失败。</returns>
        public bool FileDelete(string fullPath)
        {
            // 删除文件。
            return VBFileController.FileDelete(fullPath);
        }

        /// <summary>
        /// 用于判断服务器指定的文件是否存在。
        /// 返回:True:文件存在,false:文件不存在。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:True:文件存在,false:文件不存在。</returns>
        public bool FileExists(string fullPath)
        {
            // 判断文件是否存在。
            return VBFileController.FileExists(fullPath);
        }

        /// <summary>
        /// 用于移动源文件到指定位置,或者更改文件名称。
        /// 返回:Ture:操作成功,False:操作失败。
        /// </summary>
        /// <param name="sourceFullPath">源文件的完整路径及文件名。</param>
        /// <param name="destFullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:Ture:操作成功,False:操作失败。</returns>
        public bool FileMove(string sourceFullPath, string destFullPath)
        {
            // 判断文件是否存在。
            return VBFileController.FileMove(sourceFullPath, destFullPath);
        }

        /// <summary>
        /// 用于按行读取服务器指定文件。
        /// 返回:以字符串数组的形式返回文件中的所有行。null:读取失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:以字符串数组的形式返回文件中的所有行。null:读取失败。</returns>
        public string[] ReadAllLines(string fullPath)
        {
            // 读取目标文件。
            return VBFileController.ReadAllLines(fullPath);
        }

        /// <summary>
        /// 用于读取服务器指定文件的所有文本。
        /// 返回:文件的所有文本。"":读取失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:文件的所有文本。"":读取失败。</returns>
        public string ReadAllText(string fullPath)
        {
            // 读取目标文件。
            return VBFileController.ReadAllText(fullPath);
        }

        /// <summary>
        /// 用于以流的形式读取指定的文件。
        /// 返回:文件内容的二进制流。"":读取失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <returns>返回:文件内容的二进制流。"":读取失败。</returns>
        public byte[] ReadStream(string fullPath)
        {
            // 读取目标文件。
            return VBFileController.ReadStream(fullPath);
        }

        /// <summary>
        /// 用于按行写入服务器指定文件。文件不存在时创建新文件,文件存在时覆盖旧文件内容。
        /// 返回:Ture:写入成功,False:写入失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <param name="allLine">以字符串数组的形式保存的文件中的所有行。</param>
        /// <returns>返回:Ture:写入成功,False:写入失败。</returns>
        public bool WriteAllLines(string fullPath, string[] allLine)
        {
            // 写入目标文件。
            return VBFileController.WriteAllLines(fullPath, allLine);
        }

        /// <summary>
        /// 用于写入服务器指定文件的所有文本。文件不存在时创建新文件,文件存在时覆盖旧文件内容。
        /// 返回:Ture:写入成功,False:写入失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <param name="allText">文件的所有文本。</param>
        /// <returns>返回:Ture:写入成功,False:写入失败。</returns>
        public bool WriteAllText(string fullPath, string allText)
        {
            // 写入目标文件。
            return VBFileController.WriteAllText(fullPath, allText);
        }

        /// <summary>
        /// 用于写入服务器指定XML文件的所有文本(UTF-8)。文件不存在时创建新文件,文件存在时覆盖旧文件内容。
        /// 返回:Ture:写入成功,False:写入失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <param name="allText">文件的所有文本。</param>
        /// <returns>返回:Ture:写入成功,False:写入失败。</returns>
        public bool WriteAllTextForXml(string fullPath, string allText)
        {
            // 写入目标文件。
            return VBFileController.WriteAllTextForXml(fullPath, allText);
        }

        /// <summary>
        /// 用于以流的形式写入指定的文件。
        /// 返回:Ture:写入成功,False:写入失败。
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名。</param>
        /// <param name="fileBuffer">文件内容的二进制流。</param>
        /// <returns>返回:Ture:写入成功,False:写入失败。</returns>
        public bool WriteStream(string fullPath, byte[] fileBuffer)
        {
            // 写入目标文件。
            return VBFileController.WriteStream(fullPath, fileBuffer);
        }
        /// <summary>
        /// 获得驱动器列表
        /// </summary>
        /// <returns>驱动器列表数组</returns>
        public  string[] GetLogicDrivers()
        {
            return System.IO.Directory.GetLogicalDrives();
        }
        /// <summary>
        /// 获得驱动器剩余空间大小
        /// </summary>
        /// <param name="driverName">驱动器名</param>
        /// <returns>剩余空间大小</returns>
        public  long GetTotalFreeSpace(string driverName)
        {
            System.IO.DriveInfo driveInfo = new System.IO.DriveInfo(driverName);
            return driveInfo.TotalFreeSpace;
        }
        /// <summary>
        /// 删除文件(如果文件所在文件夹为空则删除文件夹)
        /// 返回:true:成功,false:失败
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名</param>
        /// <returns>返回:true:成功,false:失败</returns>
        public  bool RemoteDeleteFile(string fullPath)
        {
            bool delFlg = false;
            if (VBFileController.FileExists(fullPath))
            {
                delFlg=VBFileController.FileDelete(fullPath);
                string directoryPath = fullPath.Substring(0,fullPath.LastIndexOf('//'));
                while(!VBFileController.IsHasSubDirectory(directoryPath)&&!VBFileController.IsHasFiles(directoryPath)&&!directoryPath.EndsWith(":"))
                {
                   delFlg= VBFileController.DirectoryDelete(directoryPath);
                   directoryPath = directoryPath.Substring(0, directoryPath.LastIndexOf('//'));
                }
            }
            return delFlg;
        }
        /// <summary>
        /// 创建文件(如果文件存在则删除文件;如果目标文件所在文件夹不存在则创建文件夹)
        /// 返回:true:成功,false:失败
        /// </summary>
        /// <param name="fullPath">目标文件的完整路径及文件名</param>
        /// <param name="buffer">目标文件的数据流</param>
        /// <returns>返回:true:成功,false:失败</returns>
        public bool RemoteCreateFile(string fullPath,byte[] buffer)
        {
            if (VBFileController.FileExists(fullPath))
            {
                RemoteDeleteFile(fullPath);
            }
            string directoryPath = fullPath.Substring(0, fullPath.LastIndexOf('//'));
            if (!VBFileController.DirectoryExists(directoryPath))
            {
                VBFileController.DirectoryCreate(directoryPath);
            }
          
            return VBFileController.WriteStream(fullPath,buffer);
        }
    }
}

 

[VideoBackServer.Server.cs]

using System;
using System.Runtime;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
//using System.Runtime.Remoting.Channels.Http;
using System.Windows.Forms;
using VideoBack.VideoBackCommon;
using System.IO;

namespace VideoBack.VideoBackServer
{
    static class Server
    {
        /// <summary>
        /// 该方法用于提供VideoBack服务器端服务。
        /// </summary>
        [STAThread]
        static void Main()
        {
            // 生成注册Remote共享类型使用的信道。
            TcpServerChannel tcpServerChannel = new TcpServerChannel(VBRemoteFileController.REMOTE_CHANNEL);
            //HttpServerChannel httpServerChannel = new HttpServerChannel(VBRemoteFileController.REMOTE_CHANNEL);
            // 向系统信道服务注册该信道。
            ChannelServices.RegisterChannel(tcpServerChannel, false);
            //ChannelServices.RegisterChannel(httpServerChannel,false);
            // 将VBRemoteFileController类注册为共享类型,以备服务器调用。
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(VBRemoteFileController), VBRemoteFileController.REMOTE_FILE_CONTROLLER_NAME, WellKnownObjectMode.SingleCall);

            // 启动监听。
            Application.Run();
        }
    }
}

 

[VideoBackClient.OperatingFile.cs]

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace VideoBack.VideoBackClient
{
    /// <summary>
    /// 操作文件的方法
    /// </summary>
    public class OperatingFile
    {
        static OperatingFile()
        {
        }
        /// <summary>
        /// 将源文件存入数组
        /// </summary>
        /// <param name="filePath">源文件路径</param>
        /// <returns></returns>
        public static byte[] GetFileBytes(string filePath)
        {
            if (File.Exists(filePath))
            {
                try
                {
                    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    byte[] buffer = new byte[fileStream.Length];
                    fileStream.Read(buffer, 0, buffer.Length);
                    fileStream.Close();
                    return buffer;
                }
                catch
                {
                    return null;
                }
            }
            else
                return null;
        }
        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="fileBytes">源文件转化成的数组</param>
        /// <param name="savePath">目标文件的路径</param>
        /// <returns></returns>
        public static bool SendFileBytes(byte[] fileBytes, string savePath)
        {

            if (fileBytes == null) return false;

            try
            {
                FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
                fs.Write(fileBytes, 0, fileBytes.Length);
                fs.Close();
                return true;
            }
            catch
            {
                return false;
            }

        }
        /// <summary>
        /// 获得驱动器列表
        /// </summary>
        /// <returns>驱动器列表数组</returns>
        public static string[] GetLogicDrivers()
        {
            return System.IO.Directory.GetLogicalDrives();
        }
        /// <summary>
        /// 获得驱动器剩余空间大小
        /// </summary>
        /// <param name="driverName">驱动器名</param>
        /// <returns>剩余空间大小</returns>
        public static long GetTotalFreeSpace(string driverName)
        {
            System.IO.DriveInfo driveInfo=new DriveInfo(driverName);
            return driveInfo.TotalFreeSpace;
        }

    }
}

[VideoBackClient.SQLManager.cs]

 

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;

namespace VideoBack.VideoBackClient
{
     public class SQLManager
    {

        static string server = Properties.Settings.Default.Server;
        static string userId = Properties.Settings.Default.UserID;
        static string password = Properties.Settings.Default.Password;
        static string dataBase = Properties.Settings.Default.DataBase;
         //建立数据库连接
        static SqlConnection sqlConnection = new SqlConnection(string.Format("server={0};uid={1};pwd={2};database={3}",server,userId,password,dataBase));
        /// <summary>
        /// 查询数据并保存到datatable中
        /// </summary>
        /// <param name="SelectString">数据库查询语句</param>
        /// <returns>成功返回datatable;不成功返回null</returns>
        public static DataTable SelectDataToDataTable(string SelectString)
        {
            try
            {
                DataTable dataTable = new DataTable();
                SqlCommand sqlCommand = new SqlCommand(SelectString, sqlConnection);
                sqlConnection.Open();
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
                sqlConnection.Close();
                sqlDataAdapter.Fill(dataTable);
                return dataTable;
            }
            catch
            {
                sqlConnection.Close();
                return null;
            }
        }
         /// <summary>
         /// 执行sql语句
         /// </summary>
         /// <param name="sqlString">sql语句</param>
         /// <returns>成功返回:true;不成功返回:false</returns>
        public static bool ExecuteSQL(string sqlString)
        {
            try
            {
                SqlCommand sqlCommand = new SqlCommand(sqlString, sqlConnection);
                sqlConnection.Open();
                sqlCommand.ExecuteNonQuery();
                sqlConnection.Close();
                return true;
            }
            catch
            {
                sqlConnection.Close();
                return false;
            }
        }

    }
}

[VideoBackClient.Client.cs]

 

using System;
using System.Data;
using System.Net;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
//using System.Runtime.Remoting.Channels.Http;
using VideoBack.VideoBackCommon;
using System.Threading;

namespace VideoBack.VideoBackClient
{
    static class Client
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // 生成注册Remote共享类型使用的信道。
            TcpClientChannel tcpClientChannel = new TcpClientChannel();
            //HttpClientChannel httpClientChannel = new HttpClientChannel();
            // 向系统信道服务注册该信道。
            ChannelServices.RegisterChannel(tcpClientChannel, false);
            //ChannelServices.RegisterChannel(httpClientChannel,false);
            //获得本地的ip地址
            string hostName = Dns.GetHostName();
            IPHostEntry iPHostEntry = Dns.GetHostEntry(hostName);
            IPAddress iPAdress = iPHostEntry.AddressList[0];
            // 获得客户端VBRemoteFileController共享类型的实例。
            VBRemoteFileController vBRemoteFileController = (VBRemoteFileController)Activator.GetObject(
                    typeof(VBRemoteFileController), string.Format("tcp://{0}:{1}/{2}",iPAdress,VBRemoteFileController.REMOTE_CHANNEL,VBRemoteFileController.REMOTE_FILE_CONTROLLER_NAME));
            //VBRemoteFileController vBRemoteFileController = (VBRemoteFileController)Activator.GetObject(
            //    typeof(VBRemoteFileController), "http://192.168.1.110:4022/VBRemoteFileController");
            ///获取事件的间隔时间
            long timeBetweenEvent=Convert.ToInt32(Properties.Settings.Default.TimeBetweenEvent)*60*1000;
            //定时启动复制进程。参数1:定时启动的方法;参数2:向方法传递的参数;参数3:首次启动延时时间(毫秒计时);参数4:启动进程的时间间隔(毫秒计时)。
            System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(TimerCall), vBRemoteFileController, 0, timeBetweenEvent);

            Application.Run();
        }
        /// <summary>
        /// 由timer控制的定时运行程序
        /// </summary>
        /// <param name="b">参数</param>
        public static void TimerCall(object b)
        {
            VBRemoteFileController vBRemoteFileController = (VBRemoteFileController)b;
            string[] driverNames = OperatingFile.GetLogicDrivers();
            DataTable dataTable = SQLManager.SelectDataToDataTable(@"SELECT * FROM IDVR_RECORD_Files ORDER BY bTime DESC");
            byte[] byteBuffer=null;
            string sourcePath="";
            int i, j, k;
            if (dataTable.Rows.Count != 0 && driverNames.Length != 0)
            {
                for (i = 0; i < dataTable.Rows.Count; i++)
                {
                    DataTable backDataTable = SQLManager.SelectDataToDataTable(@"SELECT * FROM IDVR_RECORD_BACKUP WHERE SourceFilePath  LIKE  '%" + GetFilePath(dataTable.Rows[i],"")+"'");
                    if (backDataTable.Rows.Count != 0) break;
                    for (j = driverNames.Length-1; j >=0; j--)
                    {
                        sourcePath = GetFilePath(dataTable.Rows[i], driverNames[j]);
                        if (vBRemoteFileController.FileExists(sourcePath))
                        {
                            byteBuffer = OperatingFile.GetFileBytes(sourcePath);
                            break;
                        }
                    }
                    if (byteBuffer != null)
                    {
                        string[] destDriverNames = vBRemoteFileController.GetLogicDrivers();
                        int start=0;
                        for (start = 0; start < destDriverNames.Length; start++)
                        {
                            if (Properties.Settings.Default.BackStartDriverName != null)
                            {
                                if (destDriverNames[start].Substring(0,1) == Properties.Settings.Default.BackStartDriverName.Substring(0,1)) break;
                            }
                        }
                        for (k = start; k < destDriverNames.Length; k++)
                        {
                            if (vBRemoteFileController.GetTotalFreeSpace(destDriverNames[k]) > byteBuffer.Length)
                            {
                                string destPath = GetFilePath(dataTable.Rows[i], destDriverNames[k]);
                                vBRemoteFileController.RemoteCreateFile(destPath, byteBuffer);
                                backDataTable = SQLManager.SelectDataToDataTable(@"SELECT MAX(CONVERT(numeric, DestID)) AS DestID FROM IDVR_RECORD_BACKUP ");
                                string destID="";
                                if (!string.IsNullOrEmpty(Convert.ToString(backDataTable.Rows[0]["DestID"])))
                                {
                                    destID = Convert.ToString(Convert.ToInt32(backDataTable.Rows[0]["DestID"]) + 1);
                                }
                                else
                                {
                                    destID = "1";
                                }
                                SQLManager.ExecuteSQL(@"INSERT INTO IDVR_RECORD_BACKUP(DestID, DestFilePath, SourceFilePath, SourceID) VALUES ('" + destID + "','" + destPath + "','" + sourcePath + "','" + Convert.ToString(dataTable.Rows[i]["ID"]) + "')");
                                break;

                            }
                        }
                        if (k >= destDriverNames.Length)
                        {
                            backDataTable = SQLManager.SelectDataToDataTable(@"SELECT TOP 1 DestID, DestFilePath, SourceFilePath, SourceID FROM IDVR_RECORD_BACKUP ORDER BY CONVERT(int, SourceID)");
                            if (backDataTable.Rows.Count != 0)
                            {
                                if (SQLManager.ExecuteSQL(@"DELETE FROM IDVR_RECORD_BACKUP WHERE DestID='" + Convert.ToString(backDataTable.Rows[0]["DestID"]) + "'"))
                                {
                                    string oldDestPath=Convert.ToString( backDataTable.Rows[0]["DestFilePath"]);
                                    vBRemoteFileController.RemoteDeleteFile(oldDestPath);
                                    string destPath = oldDestPath.Substring(0, oldDestPath.IndexOf(":") + 2) + GetFilePath(dataTable.Rows[i],"");
                                    vBRemoteFileController.RemoteCreateFile(destPath, byteBuffer);
                                    backDataTable = SQLManager.SelectDataToDataTable(@"SELECT MAX(CONVERT(numeric, DestID)) AS DestID FROM IDVR_RECORD_BACKUP ");
                                    string destID = "";
                                    if (!string.IsNullOrEmpty(Convert.ToString(backDataTable.Rows[0]["DestID"])))
                                    {
                                        destID = Convert.ToString(Convert.ToInt32(backDataTable.Rows[0]["DestID"]) + 1);
                                    }
                                    else
                                    {
                                        destID = "1";
                                    }
                                    SQLManager.ExecuteSQL(@"INSERT INTO IDVR_RECORD_BACKUP(DestID, DestFilePath, SourceFilePath, SourceID) VALUES ('" + destID + "','" + destPath + "','" + sourcePath + "','" + Convert.ToString(dataTable.Rows[i]["ID"]) + "')");
                                }
                            }

                        }
                    }
                }

            }
        }

        /// <summary>
        /// 获得文件路径
        /// </summary>
        /// <param name="dataRow">数据表中的一行记录</param>
        /// <param name="driverName">驱动器名</param>
        /// <returns>文件的路径</returns>
        public static string GetFilePath(DataRow dataRow,string driverName)
        {
            string startDate = (Convert.ToDateTime(dataRow["bTime"])).ToString("yyyy-MM-dd");
            string startTime = (Convert.ToDateTime(dataRow["bTime"])).ToString("HH-mm-ss");
            string endTime = (Convert.ToDateTime(dataRow["eTime"])).ToString("HH-mm-ss");
            string cameraID = dataRow["CamID"].ToString();
            string sourcePath = driverName+"Datafiles//data//" + startDate + "//{" + cameraID + "}//" + startTime + "_" + endTime + ".A64";
            return sourcePath;
        }


    }
}

 

[VideoBackClient.app.config]

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="VideoBack.VideoBackServer.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <applicationSettings>
        <VideoBack.VideoBackServer.Properties.Settings>
            <setting name="BackStartDriverName" serializeAs="String">
                <value>E://</value>
            </setting>
            <setting name="TimeBetweenEvent" serializeAs="String">
                <value>5</value>
            </setting>
            <setting name="Server" serializeAs="String">
                <value>localhost</value>
            </setting>
            <setting name="UserID" serializeAs="String">
                <value>sa</value>
            </setting>
            <setting name="Password" serializeAs="String">
                <value>sa</value>
            </setting>
            <setting name="DataBase" serializeAs="String">
                <value>idvrDirectory</value>
            </setting>
        </VideoBack.VideoBackServer.Properties.Settings>
    </applicationSettings>
</configuration>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值