Three solutions for uploading large files with .NET

FileUpLoad can be used for ASP.NET uploading files, but FileUpLoad can not be used to operate the folder.

The following example uses ASP.NET to upload folders and compress and decompress the folders.

ASP.NET page design: TextBox and Button buttons.

In TextBox, you need to receive the path of the input folder (including the folder). The problem of selecting the folder through the Button has not been solved. For the time being, you can only enter it manually.

Two methods: generate rar and zip.

1. Generate rar

using Microsoft.Win32;

using System.Diagnostics;

protected void Button1Click(object sender, EventArgs e)

    {

        RAR(@"E:\95413594531\GIS", "tmptest", @"E:\95413594531\");

    }

    ///

   /// Compressed file

   ///

   /// Folder or single file that needs to be compressed

   /// The file name of the generated compressed file

   /// Generate compressed file save path

   ///

    protected bool RAR(string DFilePath, string DRARName,string DRARPath)

    {

        String therar;

        RegistryKey theReg;

        Object theObj;

        String theInfo;

        ProcessStartInfo theStartInfo;

        Process theProcess;

        try

        {

            theReg = Registry.ClassesRoot.OpenSubKey (@ "Applications \ WinRAR.exe \ Shell \ Open \ Command"); // Note: This path was not found in the root path of the registry

            theObj = theReg.GetValue("");

            therar = theObj.ToString();

            theReg.Close();

            therar = therar.Substring(1, therar.Length - 7);

            theInfo = "a" + "" + DRARName + "" + DFilePath + "-ep1"; // Command + file name after compression + compressed file or path

            theStartInfo = new ProcessStartInfo();

            theStartInfo.FileName = therar;

            theStartInfo.Arguments = theInfo;

            theStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            theStartInfo.WorkingDirectory = DRARPath; // The storage directory of the RaR file.

            theProcess = new Process();

            theProcess.StartInfo = theStartInfo;

            theProcess.Start();

            theProcess.WaitForExit();

            theProcess.Close();

            return true;

        }

        catch (Exception ex)

        {

            return false;

        }

    }

 

    ///

    /// Unzip to the specified folder

    ///

    /// Directory where compressed files exist

    /// compressed file name

    /// Extract to folder

    ///

    protected bool UnRAR(string RARFilePath,string RARFileName,string UnRARFilePath)

    {

        //unzip

        String therar;

        RegistryKey theReg;

        Object theObj;

        String theInfo;

        ProcessStartInfo theStartInfo;

        Process theProcess;

        try

         {

            theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");

            theObj = theReg.GetValue("");

            therar = theObj.ToString();

            theReg.Close();

            therar = therar.Substring(1, therar.Length - 7);

            theInfo = @" X " + " " + RARFilePath + RARFileName + " " + UnRARFilePath;

            theStartInfo = new ProcessStartInfo();

            theStartInfo.FileName = therar;

            theStartInfo.Arguments = theInfo;

            theStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            theProcess = new Process();

            theProcess.StartInfo = theStartInfo;

            theProcess.Start();

            return true;

        }

        catch (Exception ex)

         {

             return false;

         }

    }

Note: This method does not find the proper path in the computer registry, it is not implemented, and it is for reference only.

2. Generate zip

By calling the class library ICSharpCode.SharpZipLib.dll

The library can be downloaded from the Internet. It can also be downloaded from this link: SharpZipLib_0860_Bin.zip

Add two categories: Zip.cs and UnZip.cs

(1)Zip.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

using System.IO;

using System.Collections;

using ICSharpCode.SharpZipLib.Checksums;

using ICSharpCode.SharpZipLib.Zip;

 

 

namespace UpLoad

{

    /// <summary>

    /// Function: Compressed files

    /// creator chaodongwang 2009-11-11

    /// </summary>

    public class Zip

    {

        /// <summary>

        /// Compress a single file

        /// </summary>

        /// <param name = "FileToZip"> The name of the compressed file (including the file path) </ param>

        /// <param name = "ZipedFile"> Zipped file name (including file path) </ param>

        /// <param name = "CompressionLevel"> Compression rate 0 (no compression) -9 (highest compression rate) </ param>

        /// <param name = "BlockSize"> cache size </ param>

        public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel)

        {

            // If the file is not found, an error is reported

            if (!System.IO.File.Exists(FileToZip))

            {

                throw new System.IO.FileNotFoundException ("File:" + FileToZip + "Not found!");

            }

 

            if (ZipedFile == string.Empty)

            {

                ZipedFile = Path.GetFileNameWithoutExtension(FileToZip) + ".zip";

            }

 

            if (Path.GetExtension(ZipedFile) != ".zip")

            {

                ZipedFile = ZipedFile + ".zip";

            }

 

            //// If the specified location directory does not exist, create the directory

            //string zipedDir = ZipedFile.Substring(0,ZipedFile.LastIndexOf("\\"));

            //if (!Directory.Exists(zipedDir))

            //    Directory.CreateDirectory(zipedDir);

 

            // The name of the compressed file

            string filename = FileToZip.Substring(FileToZip.LastIndexOf('\\') + 1);

           

            System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);

            ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);

            ZipEntry ZipEntry = new ZipEntry(filename);

            ZipStream.PutNextEntry(ZipEntry);

            ZipStream.SetLevel(CompressionLevel);

            byte[] buffer = new byte[2048];

            System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);

            ZipStream.Write(buffer, 0, size);

            try

            {

                while (size < StreamToZip.Length)

                {

                    int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);

                    ZipStream.Write(buffer, 0, sizeRead);

                    size += sizeRead;

                }

            }

            catch (System.Exception ex)

            {

                throw ex;

            }

            finally

            {

                ZipStream.Finish();

                ZipStream.Close();

                StreamToZip.Close();

            }

        }

 

        /// <summary>

        /// How to compress folders

        /// </summary>

        public void ZipDir(string DirToZip, string ZipedFile, int CompressionLevel)

        {

            // When the compressed file is empty, the default is the same directory as the compressed folder

            if (ZipedFile == string.Empty)

            {

                ZipedFile = DirToZip.Substring(DirToZip.LastIndexOf("\\") + 1);

                ZipedFile = DirToZip.Substring(0, DirToZip.LastIndexOf("\\")) +"\\"+ ZipedFile+".zip";

            }

 

            if (Path.GetExtension(ZipedFile) != ".zip")

            {

                ZipedFile = ZipedFile + ".zip";

            }

 

            using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(ZipedFile)))

            {

                zipoutputstream.SetLevel(CompressionLevel);

                Crc32 crc = new Crc32();

                Hashtable fileList = getAllFies(DirToZip);

                foreach (DictionaryEntry item in fileList)

                {

                    FileStream fs = File.OpenRead(item.Key.ToString());

                    byte[] buffer = new byte[fs.Length];

                    fs.Read(buffer, 0, buffer.Length);

                    ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(DirToZip.Length + 1));

                    entry.DateTime = (DateTime)item.Value;

                    entry.Size = fs.Length;

                    fs.Close();

                    crc.Reset();

                    crc.Update(buffer);

                    entry.Crc = crc.Value;

                    zipoutputstream.PutNextEntry(entry);

                    zipoutputstream.Write(buffer, 0, buffer.Length);

                }

            }

        }

 

        /// <summary>

        /// Get all files

        /// </summary>

        /// <returns></returns>

        private Hashtable getAllFies(string dir)

        {

            Hashtable FilesList = new Hashtable();

            DirectoryInfo fileDire = new DirectoryInfo(dir);

            if (!fileDire.Exists)

            {

                throw new System.IO.FileNotFoundException ("Directory:" + fileDire.FullName + "Not Found!");

            }

 

            this.getAllDirFiles(fileDire, FilesList);

            this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);

            return FilesList;

        }

        /// <summary>

        /// Get files in all folders under one folder

        /// </summary>

        /// <param name="dirs"></param>

        /// <param name="filesList"></param>

        private void getAllDirsFiles(DirectoryInfo[] dirs, Hashtable filesList)

        {

            foreach (DirectoryInfo dir in dirs)

            {

                foreach (FileInfo file in dir.GetFiles("*.*"))

                {

                    filesList.Add(file.FullName, file.LastWriteTime);

                }

                this.getAllDirsFiles (dir.GetDirectories (), filesList);

            }

        }

        /// <summary>

        /// Get files in a folder

        /// </summary>

        /// <param name = "strDirName"> directory name </ param>

        /// <param name = "filesList"> file list HastTable </ param>

        private void getAllDirFiles(DirectoryInfo dir, Hashtable filesList)

        {

            foreach (FileInfo file in dir.GetFiles("*.*"))

            {

                filesList.Add(file.FullName, file.LastWriteTime);

            }

        }

    }

}

(2)UnZip.cs

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

/// <summary>

/// unzip files

/// </summary>

 

using System;

using System.Text;

using System.Collections;

using System.IO;

using System.Diagnostics;

using System.Runtime.Serialization.Formatters.Binary;

using System.Data;

 

using ICSharpCode.SharpZipLib.Zip;

using ICSharpCode.SharpZipLib.Zip.Compression;

using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

 

namespace UpLoad

{

    /// <summary>

    /// Function: unzip file

    /// creator chaodongwang 2009-11-11

    /// </summary>

    public class UnZipClass

    {

        /// <summary>

        /// Function: Unzip the file in zip format.

        /// </summary>

        /// <param name = "zipFilePath"> zip file path </ param>

        /// <param name = "unZipDir"> The storage path of the decompressed file, when it is empty, the default is the same level as the compressed file, and the folder with the same name as the compressed file </ param>

        /// <param name = "err"> Error message </ param>

        /// <returns> Whether the decompression is successful </ returns>

        public void UnZip(string zipFilePath, string unZipDir)

        {

            if (zipFilePath == string.Empty)

            {

                throw new Exception ("The compressed file cannot be empty!");

            }

            if (!File.Exists(zipFilePath))

            {

                throw new System.IO.FileNotFoundException ("Zipped file does not exist!");

            }

            // When the unzipped folder is empty, it defaults to the same level directory as the compressed file, and the folder with the same name as the compressed file

            if (unZipDir == string.Empty)

                unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));

            if (!unZipDir.EndsWith("\\"))

                unZipDir += "\\";

            if (!Directory.Exists(unZipDir))

                Directory.CreateDirectory(unZipDir);

 

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))

            {

 

                ZipEntry theEntry;

                while ((theEntry = s.GetNextEntry()) != null)

                {

                    string directoryName = Path.GetDirectoryName(theEntry.Name);

                    string fileName = Path.GetFileName(theEntry.Name);

                    if (directoryName.Length > 0)

                    {

                        Directory.CreateDirectory(unZipDir + directoryName);

                    }

                    if (!directoryName.EndsWith("\\"))

                        directoryName += "\\";

                    if (fileName != String.Empty)

                    {

                        using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))

                        {

 

                            int size = 2048;

                            byte[] data = new byte[2048];

                            while (true)

                            {

                                size = s.Read(data, 0, data.Length);

                                if (size > 0)

                                {

                                    streamWriter.Write(data, 0, size);

                                }

                                else

                                {

                                    break;

                                }

                            }

                        }

                    }

                }

            }

        }

    }

}

The above two class libraries can be created directly in the program, then copied and pasted, and directly called.

The main program code is as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Drawing;

 

using Microsoft.Win32;

using System.Diagnostics;

 

 

namespace UpLoad

{

    public partial class UpLoadForm : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protected void Button1_Click(object sender, EventArgs e)

        {

            if (TextBox1.Text == "") // If the input is empty, a prompt will pop up

            {

                this.Response.Write ("<script> alert ('The input is empty, please re-enter!'); window.opener.location.href = window.opener.location.href; </ script>");

            }

            else

            {

                // Zipped folder

                string zipPath = TextBox1.Text.Trim (); // Get the path to be compressed (including folder)

                string zipedPath = @ "c: \ temp"; // The path of the compressed folder (including the folder)

                Zip Zc = new Zip();

                Zc.ZipDir (zipPath, zipedPath, 6);

                this.Response.Write("<script>alert('压缩成功!');window.opener.location.href=window.opener.location.href;</script>");

 

                // Unzip the folder

                UnZipClass unZip = new UnZipClass();

                unZip.UnZip (zipedPath + ".zip", @ "c: \ temp"); // The path (including file name) and decompression path of the folder to be decompressed (the files in the temp folder are the files in the input path folder )

                this.Response.Write("<script>alert('解压成功!');window.opener.location.href=window.opener.location.href;</script>");

 

            }

        }

    }

}

This method has been tested and realized.

In addition, another method of uploading files is attached, which has been achieved after testing. Refer to the link: http://blog.ncmem.com/wordpress/2019/11/20/net%e4%b8%8a%e4%bc%a0 % e5% a4% a7% e6% 96% 87% e4% bb% b6% e7% 9a% 84% e8% a7% a3% e5% 86% b3% e6% 96% b9% e6% a1% 88 / 

Welcome to join the group to discuss: 374992201

 

Guess you like

Origin www.cnblogs.com/songsu/p/12690896.html