⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 service.cs

📁 Asp.net在线WEB文件管理,以及通过WebService在线搜索文件
💻 CS
📖 第 1 页 / 共 3 页
字号:
    /// <param name="ticket">加密票</param>
    /// <param name="Name">路径</param>
    /// <returns>成功返回属性值,否则返回空</returns>
    [WebMethod(Description = "属性 需要提供合法票据")]
    public string Attribute(string ticket, string Name)
    {
        if (IsTicketValid(ticket,false))
        {
            string Results = string.Empty;
            string Path = rootdir + FormsAuthentication.Decrypt(ticket).Name + Name;
            UploadPath = rootdir + FormsAuthentication.Decrypt(ticket).Name;
            DirectoryInfo dirAll = new DirectoryInfo(UploadPath);
            long CurrSize = DirSize(dirAll);
            long AllowSize = CheckSize(FormsAuthentication.Decrypt(ticket).Name);
            Results += "总共:" + FormatFileSize(AllowSize);
            Results += "|已用:" + FormatFileSize(CurrSize);
            Results += "|剩余:" + FormatFileSize(AllowSize - CurrSize);

            Results += "|创建时间:" + File.GetCreationTime(Path);
            Results += "|修改时间:" + File.GetLastWriteTime(Path);

            FileInfo file = new FileInfo(Path);
            DirectoryInfo dir = new DirectoryInfo(Path);
            ///判断当前是否是文件夹
            if ((file.Attributes & FileAttributes.Directory) != 0)
            {
                ///如果是文件夹
                Results += "|大小:" + FormatFileSize(DirSize(dir));
                int DirCount = dir.GetDirectories().GetLength(0);
                int FileCount = dir.GetFiles().GetLength(0);

                Results += "|共有文件夹 " + DirCount.ToString() + " 个|";
                Results += "文件 " + FileCount.ToString() + " 个";
            }
            else
            {
                ///如果是文件
                Results += "|大小:" + FormatFileSize(GetFileSize(ticket, Name));
            }
            return Results;
        }
        else return null;
    }

    /// <summary>
    /// 得到目录大小
    /// </summary>
    /// <param name="d">目录名</param>
    /// <returns>大小</returns>
    private static long DirSize(DirectoryInfo d)
    {
        long Size = 0;
        /// 所有文件大小.
        FileInfo[] fis = d.GetFiles();
        foreach (FileInfo fi in fis)
        {
            Size += fi.Length;
        }
        /// 遍历出当前目录的所有文件夹.
        DirectoryInfo[] dis = d.GetDirectories();
        foreach (DirectoryInfo di in dis)
        {
            Size += DirSize(di);   ///递归调用
        }
        return Size;
    }

    /// <summary>
    /// 文件大小格式化
    /// </summary>
    /// <param name="numBytes">原始大小</param>
    /// <returns>格式化后的大小</returns>
    private static string FormatFileSize(long numBytes)
    {
        string fileSize = "";

        if (numBytes > 1073741824)
            fileSize = String.Format("{0:0.00} GB", (double)numBytes / 1073741824);
        else if (numBytes > 1048576)
            fileSize = String.Format("{0:0.00} MB", (double)numBytes / 1048576);
        else
            fileSize = String.Format("{0:0} KB", (double)numBytes / 1024);

        if (fileSize == "0 KB")
            fileSize = "1 KB";							
        return fileSize;
    }

    #endregion

    #region Upload
    /// <summary>
    /// Append a chunk of bytes to a file.
    /// The client must ensure that all messages are in sequence. 
    /// This method always overwrites any existing file with the same name
    /// </summary>
    /// <param name="FileName">The name of the file that this chunk belongs to, e.g. MyImage.TIFF</param>
    /// <param name="buffer">The byte array</param>
    /// <param name="Offset">The size of the file (if the server reports a different size, an exception is thrown)</param>
    /// <param name="BytesRead">The length of the buffer</param>
    [WebMethod(Description = "上传文件 需要提供合法票据")]
    public string AppendChunk(string ticket,string FileName, byte[] buffer, long Offset, int BytesRead,long FullSize)
    {
        if (IsTicketValid(ticket,false))
        {
            object username = FormsAuthentication.Decrypt(ticket).Name;
            UploadPath = rootdir + username + "\\";
            DirectoryInfo dir = new DirectoryInfo(UploadPath);
            long CurrSize = DirSize(dir);
            CurrSize += FullSize;
            long AllowSize = CheckSize(username.ToString());

            if (CurrSize > AllowSize)
                return "Not Enough Space";

            string FilePath = UploadPath + FileName;

            // make sure that the file exists, except in the case where the file already exists and offset=0, i.e. a new upload, in this case create a new file to overwrite the old one.
            bool FileExists = File.Exists(FilePath);
            if (!FileExists || (File.Exists(FilePath) && Offset == 0))
                File.Create(FilePath).Close();
            long FileSize = new FileInfo(FilePath).Length;

            // if the file size is not the same as the offset then something went wrong....
            if (FileSize != Offset)
                CustomSoapException("Transfer Corrupted", String.Format("The file size is {0}, expected {1} bytes", FileSize, Offset));
            else
            {
                // offset matches the filesize, so the chunk is to be inserted at the end of the file.
                using (FileStream fs = new FileStream(FilePath, FileMode.Append))
                    fs.Write(buffer, 0, BytesRead);
            }
            return null;
        }
        else
            return "验证失败!"; 
    }
    #endregion

    #region Check

    /// <summary>
    /// 检查空间大小
    /// </summary>
    /// <param name="UserName">用户名</param>
    /// <returns>空间大小</returns>
    private long CheckSize(string UserName)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnStr"]);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "select disksize from users where name='" + UserName + "'";
        cmd.Connection = conn;
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        long size = 0;
        if (dr.Read())
        {
            size = Convert.ToInt64(dr["disksize"].ToString());
        }
        size = size * 1024 * 1024;
        return size;
    }

    /// <summary>
    /// 检查下载速度
    /// </summary>
    /// <param name="UserName">用户名</param>
    /// <returns>速度</returns>
    private int CheckSpeed(string UserName)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnStr"]);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "select speed from users where name='" + UserName + "'";
        cmd.Connection = conn;
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        int size = 0;
        if (dr.Read())
        {
            size = Convert.ToInt32(dr["speed"].ToString());
        }
        size = size * 1024;
        return size;
    }
    #endregion

    #region File Hashing

    /// <summary>
    /// 文件检查
    /// </summary>
    /// <param name="ticket">加密票</param>
    /// <param name="FileName">文件名</param>
    /// <returns>hash</returns>
    [WebMethod(Description = "检查文件 需要提供合法票据")]
    public string CheckFileHash(string ticket,string FileName)
    {
        if (IsTicketValid(ticket,false))
        {
            object username = FormsAuthentication.Decrypt(ticket).Name;
            UploadPath = rootdir + username + "\\" + FileName;

            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
            byte[] hash;
            using (FileStream fs = new FileStream(UploadPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096))
                hash = sha1.ComputeHash(fs);
            return BitConverter.ToString(hash);
        }
        else return null;
    }
    #endregion

    #region DownLoad

    /// <summary>
    /// Download a chunk of a file from the Upload folder on the server. 
    /// </summary>
    /// <param name="FileName">The FileName to download</param>
    /// <param name="Offset">The offset at which to fetch the next chunk</param>
    /// <param name="BufferSize">The size of the chunk</param>
    /// <returns>The chunk as a byte[]</returns>
    [WebMethod(Description = "下载文件 需要提供合法票据")]
    public byte[] DownloadChunk(string ticket, string FileName, long Offset, int BufferSize)
    {
        if (IsTicketValid(ticket,false))
        {
            object username = FormsAuthentication.Decrypt(ticket).Name;
            UploadPath = rootdir + username + "\\";

            string FilePath = UploadPath + FileName;

            /// check that requested file exists
            if (!File.Exists(FilePath))
                CustomSoapException("File not found", "The file " + FilePath + " does not exist");

            long FileSize = new FileInfo(FilePath).Length;

            /// if the requested Offset is larger than the file, bail out.
            if (Offset > FileSize)
                CustomSoapException ("Invalid Download Offset", String.Format("The file size is {0}, received request for offset {1}", FileSize, Offset));

            int pack = 10240;
            int _speed = CheckSpeed(username.ToString());
            int sleep = (int)Math.Floor(Convert.ToDouble(1000 * pack / _speed)) + 1;

            /// open the file to return the requested chunk as a byte[]
            byte[] TmpBuffer;
            int BytesRead;
            using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
            {
                fs.Seek(Offset, SeekOrigin.Begin);	// this is relevent during a retry. otherwise, it just seeks to the start
                TmpBuffer = new byte[BufferSize];
                BytesRead = fs.Read(TmpBuffer, 0, BufferSize);	// read the first chunk in the buffer (which is re-used for every chunk)
                System.Threading.Thread.Sleep(sleep);
            }
            if (BytesRead != BufferSize)
            {
                // the last chunk will almost certainly not fill the buffer, so it must be trimmed before returning
                byte[] TrimmedBuffer = new byte[BytesRead];
                Array.Copy(TmpBuffer, TrimmedBuffer, BytesRead);
                return TrimmedBuffer;
            }
            else
                return TmpBuffer;
        }
        else return null;
    }

    /// <summary>
    /// Get the number of bytes in a file in the Upload folder on the server.
    /// The client needs to know this to know when to stop downloading
    /// </summary>
    [WebMethod(Description = "取得文件大小 需要提供合法票据")]
    public long GetFileSize(string ticket, string FileName)
    {
        if (IsTicketValid(ticket,false))
        {
            object username = FormsAuthentication.Decrypt(ticket).Name;
            UploadPath = rootdir + username;

            string FilePath = UploadPath + FileName;

            /// check that requested file exists
            if (!File.Exists(FilePath))
                CustomSoapException("File not found", "The file " + FilePath + " does not exist");

            return new FileInfo(FilePath).Length;
        }
        else return 0;
    }
    #endregion

    #region Exception Handling
    /// <summary>
    /// Throws a soap exception.  It is formatted in a way that is more readable to the client, after being put through the xml serialisation process
    /// Typed exceptions don't work well across web services, so these exceptions are sent in such a way that the client
    /// can determine the 'name' or type of the exception thrown, and any message that went with it, appended after a : character.
    /// </summary>
    /// <param name="exceptionName"></param>
    /// <param name="message"></param>
    public static void CustomSoapException(string exceptionName, string message)
    {
        throw new System.Web.Services.Protocols.SoapException(exceptionName + ": " + message, new System.Xml.XmlQualifiedName("BufferedUpload"));
    }
    #endregion

    #region Register
    /// <summary>
    /// 用户注册
    /// </summary>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -