[C#] 공통 도구 클래스 - 파일 작업 클래스
                                            
 23624 단어  파일 작업
                    
/// <para> FilesUpload:    :ASP.NET       </para>
    /// <para> FileExists:        </para>
    /// <para> IsImgFilename:                       </para>
    /// <para> CopyFiles:           </para>
    /// <para> MoveFiles:           </para>
    /// <para> DeleteDirectoryFiles:               </para>
    /// <para> DeleteFiles:            </para>
    /// <para> CreateDirectory:      </para>
    /// <para> CreateDirectory:     </para>
    /// <para> ReNameFloder:      </para>
    /// <para> DeleteDirectory:      </para>
    /// <para> DirectoryIsExists:        [+2    ]</para>
    /// <para> DeleteSubDirectory:            ,             </para>
    /// <para> GetFileWriteTime:          </para>
    /// <para> GetFileExtension:             </para>
    /// <para> IsHiddenFile:         </para>
    /// <para> ReadTxtFile:           </para>
    /// <para> WriteStrToTxtFile:         (    path     ,      )</para>
    /// <para> GetLocalDrives:          </para>
    /// <para> GetAppCurrentDirectory:                </para>
    /// <para> GetFileSize:        B,KB,GB,TB    [+2   ]</para>
    /// <para> DownLoadFiles:    </para>
view sourceprint?
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Security;
using System.IO;
using System.IO.Compression;
using System.Xml;
using System.Diagnostics;
using System.Windows.Forms;
using System.Threading;
 
namespace Utils
{
    /// <summary>
    /// <para> </para>
    ///       ——     
    /// <para> ---------------------------------------------------------------------------------------</para>
    /// <para> FilesUpload:    :ASP.NET       </para>
    /// <para> FileExists:        </para>
    /// <para> IsImgFilename:                       </para>
    /// <para> CopyFiles:           </para>
    /// <para> MoveFiles:           </para>
    /// <para> DeleteDirectoryFiles:               </para>
    /// <para> DeleteFiles:            </para>
    /// <para> CreateDirectory:      </para>
    /// <para> CreateDirectory:     </para>
    /// <para> ReNameFloder:      </para>
    /// <para> DeleteDirectory:      </para>
    /// <para> DirectoryIsExists:        [+2    ]</para>
    /// <para> DeleteSubDirectory:            ,             </para>
    /// <para> GetFileWriteTime:          </para>
    /// <para> GetFileExtension:             </para>
    /// <para> IsHiddenFile:         </para>
    /// <para> ReadTxtFile:           </para>
    /// <para> WriteStrToTxtFile:         (    path     ,      )</para>
    /// <para> GetLocalDrives:          </para>
    /// <para> GetAppCurrentDirectory:                </para>
    /// <para> GetFileSize:        B,KB,GB,TB    [+2   ]</para>
    /// <para> DownLoadFiles:    </para>
    /// </summary>
    public class FilesHelper
    {
        private const string PATH_SPLIT_CHAR = "\\";
 
        #region     :ASP.NET       
        /// <summary>
        ///     :       
        /// </summary>
        /// <param name="myFileUpload">     ID</param>
        /// <param name="allowExtensions">            , :string[] allowExtensions = { ".doc", ".xls", ".ppt", ".jpg", ".gif" };</param>
        /// <param name="maxLength">         , M   </param>
        /// <param name="savePath">       ,       , :Server.MapPath("~/upload/");</param>
        /// <param name="saveName">      ,   ""        </param>
        public static void FilesUpload(FileUpload myFileUpload, string[] allowExtensions, int maxLength, string savePath, string saveName)
        {
            //           
            bool fileAllow = false;
            //        
            if (myFileUpload.HasFile)
            {
                //       , ContentLength      ,  M      2 1024
                if (myFileUpload.PostedFile.ContentLength / 1024 / 1024 >= maxLength)
                {
                    throw new Exception("      2M   !");
                }
                //            ,        
                string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower();
                string tmp = "";   //             
                //               
                for (int i = 0; i < allowExtensions.Length; i++)
                {
                    tmp += i == allowExtensions.Length - 1 ? allowExtensions[i] : allowExtensions[i] + ",";
                    if (fileExtension == allowExtensions[i])
                    {
                        fileAllow = true;
                    }
                }
                if (fileAllow)
                {
                    try
                    {
                        string path = savePath + (saveName == "" ? myFileUpload.FileName : saveName);
                        //        
                        myFileUpload.SaveAs(path);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
                else
                {
                    throw new Exception("      ,          :" + tmp);
                }
            }
            else
            {
                throw new Exception("         !");
            }
        }
        #endregion
 
        #region         
        /// <summary>
        ///         
        /// </summary>
        /// <param name="filename">   </param>
        /// <returns>    </returns>
        public static bool FileExists(string filename)
        {
            return System.IO.File.Exists(filename);
        }
        #endregion
 
        #region                        
        /// <summary>
        ///                        
        /// </summary>
        /// <param name="filename">   </param>
        /// <returns>        </returns>
        public static bool IsImgFilename(string filename)
        {
            filename = filename.Trim();
            if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
            {
                return false;
            }
            string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
            return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
        }
        #endregion
 
        #region            
        /// <summary>
        ///            
        /// </summary>
        /// <param name="sourceDir">    </param>
        /// <param name="targetDir">    </param>
        /// <param name="overWrite">   true,      ,     </param>
        /// <param name="copySubDir">   true,    ,     </param>
        public static void CopyFiles(string sourceDir, string targetDir, bool overWrite, bool copySubDir)
        {
            //        
            foreach (string sourceFileName in Directory.GetFiles(sourceDir))
            {
                string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf(PATH_SPLIT_CHAR) + 1));
 
                if (File.Exists(targetFileName))
                {
                    if (overWrite == true)
                    {
                        File.SetAttributes(targetFileName, FileAttributes.Normal);
                        File.Copy(sourceFileName, targetFileName, overWrite);
                    }
                }
                else
                {
                    File.Copy(sourceFileName, targetFileName, overWrite);
                }
            }
        }
        #endregion
 
        #region            
        /// <summary>
        ///            
        /// </summary>
        /// <param name="sourceDir">    </param>
        /// <param name="targetDir">    </param>
        /// <param name="overWrite">   true,      ,     </param>
        /// <param name="moveSubDir">   true,    ,     </param>
        public static void MoveFiles(string sourceDir, string targetDir, bool overWrite, bool moveSubDir)
        {
            //        
            foreach (string sourceFileName in Directory.GetFiles(sourceDir))
            {
                string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                if (File.Exists(targetFileName))
                {
                    if (overWrite == true)
                    {
                        File.SetAttributes(targetFileName, FileAttributes.Normal);
                        File.Delete(targetFileName);
                        File.Move(sourceFileName, targetFileName);
                    }
                }
                else
                {
                    File.Move(sourceFileName, targetFileName);
                }
            }
            if (moveSubDir)
            {
                foreach (string sourceSubDir in Directory.GetDirectories(sourceDir))
                {
                    string targetSubDir = Path.Combine(targetDir, sourceSubDir.Substring(sourceSubDir.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                    if (!Directory.Exists(targetSubDir))
                        Directory.CreateDirectory(targetSubDir);
                    MoveFiles(sourceSubDir, targetSubDir, overWrite, true);
                    Directory.Delete(sourceSubDir);
                }
            }
        }
        #endregion
 
        #region                
        /// <summary>
        ///                
        /// </summary>
        /// <param name="TargetDir">    </param>
        /// <param name="delSubDir">   true,         </param>
        public static void DeleteDirectoryFiles(string TargetDir, bool delSubDir)
        {
            foreach (string fileName in Directory.GetFiles(TargetDir))
            {
                File.SetAttributes(fileName, FileAttributes.Normal);
                File.Delete(fileName);
            }
            if (delSubDir)
            {
                DirectoryInfo dir = new DirectoryInfo(TargetDir);
                foreach (DirectoryInfo subDi in dir.GetDirectories())
                {
                    DeleteDirectoryFiles(subDi.FullName, true);
                    subDi.Delete();
                }
            }
        }
        #endregion
 
        #region             
        /// <summary>
        ///             
        /// </summary>
        /// <param name="TargetFileDir">       </param>
        public static void DeleteFiles(string TargetFileDir)
        {
            File.Delete(TargetFileDir);
        }
        #endregion
 
        #region       
        /// <summary>
        ///       
        /// </summary>
        /// <param name="targetDir"></param>
        public static void CreateDirectory(string targetDir)
        {
            DirectoryInfo dir = new DirectoryInfo(targetDir);
            if (!dir.Exists)
                dir.Create();
        }
        #endregion
 
        #region      
        /// <summary>
        ///      
        /// </summary>
        /// <param name="parentDir">    </param>
        /// <param name="subDirName">     </param>
        public static void CreateDirectory(string parentDir, string subDirName)
        {
            CreateDirectory(parentDir + PATH_SPLIT_CHAR + subDirName);
        }
        #endregion
 
        #region       
        /// <summary>
        ///       
        /// </summary>
        /// <param name="OldFloderName">        </param>
        /// <param name="NewFloderName">        </param>
        /// <returns></returns>
        public static bool ReNameFloder(string OldFloderName, string NewFloderName)
        {
            try
            {
                if (Directory.Exists(HttpContext.Current.Server.MapPath("//") + OldFloderName))
                {
                    Directory.Move(HttpContext.Current.Server.MapPath("//") + OldFloderName, HttpContext.Current.Server.MapPath("//") + NewFloderName);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion
 
        #region       
        /// <summary>
        ///       
        /// </summary>
        /// <param name="targetDir">    </param>
        public static void DeleteDirectory(string targetDir)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(targetDir);
            if (dirInfo.Exists)
            {
                DeleteDirectoryFiles(targetDir, true);
                dirInfo.Delete(true);
            }
        }
        #endregion
 
        #region         
        /// <summary>
        ///         
        /// </summary>
        /// <param name="StrPath">  </param>
        /// <returns></returns>
        public static bool DirectoryIsExists(string StrPath)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(StrPath);
            return dirInfo.Exists;
        }
        /// <summary>
        ///         
        /// </summary>
        /// <param name="StrPath">  </param>
        /// <param name="Create">     ,    </param>
        public static void DirectoryIsExists(string StrPath, bool Create)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(StrPath);
            //return dirInfo.Exists;
            if (!dirInfo.Exists)
            {
                if (Create) dirInfo.Create();
            }
        }
        #endregion
 
        #region             ,             
        /// <summary>
        ///             ,             
        /// </summary>
        /// <param name="targetDir">    </param>
        public static void DeleteSubDirectory(string targetDir)
        {
            foreach (string subDir in Directory.GetDirectories(targetDir))
            {
                DeleteDirectory(subDir);
            }
        }
        #endregion
 
        #region           
        /// <summary>
        ///           
        /// </summary>
        /// <param name="FileUrl">      </param>
        /// <returns></returns>
        public DateTime GetFileWriteTime(string FileUrl)
        {
            return File.GetLastWriteTime(FileUrl);
        }
        #endregion
 
        #region              
        /// <summary>
        ///              
        /// </summary>
        /// <param name="PathFileName">       </param>
        /// <returns></returns>
        public string GetFileExtension(string PathFileName)
        {
            return Path.GetExtension(PathFileName);
        }
        #endregion
 
        #region          
        /// <summary>
        ///          
        /// </summary>
        /// <param name="path">    </param>
        /// <returns></returns>
        public bool IsHiddenFile(string path)
        {
            FileAttributes MyAttributes = File.GetAttributes(path);
            string MyFileType = MyAttributes.ToString();
            if (MyFileType.LastIndexOf("Hidden") != -1) //      
            {
                return true;
            }
            else
                return false;
        }
        #endregion
 
        #region            
        /// <summary>
        ///            
        /// </summary>
        /// <param name="FilePath">        </param>
        /// <returns></returns>
        public static string ReadTxtFile(string FilePath)
        {
            string content = "";//      
            using (FileStream fs = new FileStream(FilePath, FileMode.Open))
            {
                using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
                {
                    string text = string.Empty;
                    while (!reader.EndOfStream)
                    {
                        text += reader.ReadLine() + "\r
";
                        content = text;
                    }
                }
            }
            return content;
        }
        #endregion
 
        #region          (    path     ,      )
        /// <summary>
        ///          (    path     ,      )
        /// </summary>
        /// <param name="FilePath">    </param>
        /// <param name="WriteStr">      </param>
        /// <param name="FileModes">    :append     , CreateNew    </param>
        public static void WriteStrToTxtFile(string FilePath, string WriteStr, FileMode FileModes)
        {
            FileStream fst = new FileStream(FilePath, FileModes);
            StreamWriter swt = new StreamWriter(fst, System.Text.Encoding.GetEncoding("utf-8"));
            swt.WriteLine(WriteStr);
            swt.Close();
            fst.Close();
        }
        #endregion
 
        #region           
        /// <summary>
        ///           
        /// </summary>
        /// <returns></returns>
        public static string[] GetLocalDrives()
        {
            return Directory.GetLogicalDrives();
        }
        #endregion
 
        #region                 
        /// <summary>
        ///                 
        /// </summary>
        /// <returns></returns>
        public static string GetAppCurrentDirectory()
        {
            return Application.StartupPath;
        }
        #endregion
 
        #region         B,KB,GB,TB    [+2   ]
        /// <summary>
        ///         B,KB,GB,TB    
        /// </summary>
        /// <param name="File">  (FileInfo  )</param>
        /// <returns></returns>
        public static string GetFileSize(FileInfo File)
        {
            string Result = "";
            long FileSize = File.Length;
            if (FileSize >= 1024 * 1024 * 1024)
            {
                if (FileSize / 1024 * 1024 * 1024 * 1024 >= 1024) Result = string.Format("{0:############0.00} TB", (double)FileSize / 1024 * 1024 * 1024 * 1024);
                else Result = string.Format("{0:####0.00} GB", (double)FileSize / 1024 * 1024 * 1024);
            }
            else if (FileSize >= 1024 * 1024) Result = string.Format("{0:####0.00} MB", (double)FileSize / 1024 * 1024);
            else if (FileSize >= 1024) Result = string.Format("{0:####0.00} KB", (double)FileSize / 1024);
            else Result = string.Format("{0:####0.00} Bytes", FileSize);
            return Result;
        }
        /// <summary>
        ///         B,KB,GB,TB    
        /// </summary>
        /// <param name="FilePath">       </param>
        /// <returns></returns>
        public static string GetFileSize(string FilePath)
        {
            string Result = "";
            FileInfo File = new FileInfo(FilePath);
            long FileSize = File.Length;
            if (FileSize >= 1024 * 1024 * 1024)
            {
                if (FileSize / 1024 * 1024 * 1024 * 1024 >= 1024) Result = string.Format("{0:########0.00} TB", (double)FileSize / 1024 * 1024 * 1024 * 1024);
                else Result = string.Format("{0:####0.00} GB", (double)FileSize / 1024 * 1024 * 1024);
            }
            else if (FileSize >= 1024 * 1024) Result = string.Format("{0:####0.00} MB", (double)FileSize / 1024 * 1024);
            else if (FileSize >= 1024) Result = string.Format("{0:####0.00} KB", (double)FileSize / 1024);
            else Result = string.Format("{0:####0.00} Bytes", FileSize);
            return Result;
        }
        #endregion
 
        #region     
        /// <summary>
        ///     
        /// </summary>
        /// <param name="FileFullPath">              </param>
        public static void DownLoadFiles(string FileFullPath)
        {
            if (!string.IsNullOrEmpty(FileFullPath) && FileExists(FileFullPath))
            {
                FileInfo fi = new FileInfo(FileFullPath);//    
                FileFullPath = HttpUtility.UrlEncode(FileFullPath); //      
                FileFullPath = FileFullPath.Replace("+", "%20"); //        "+"    
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileFullPath);
                HttpContext.Current.Response.AppendHeader("content-length", fi.Length.ToString()); //    
                int chunkSize = 102400;//     ,                 
                byte[] buffer = new byte[chunkSize]; //   
                using (FileStream fs = fi.Open(FileMode.Open))  //       
                {
                    while (fs.Position >= 0 && HttpContext.Current.Response.IsClientConnected) //             
                    {
                        int tmp = fs.Read(buffer, 0, chunkSize);//      
                        if (tmp <= 0) break; //tmp=0          ,     
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, tmp);//          
                        HttpContext.Current.Response.Flush();//        
                        Thread.Sleep(10);//       ,   CPU
                    }
                }
            }
        }
        #endregion
    }
}
  이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 읽기 및 쓰기 복사 파일 삭제 작업 방법 상세 실례 총결산1.read 세 가지 다른 방식 2. writer의 두 가지 일반적인 기본 방식 3. 삭제 삭제 동일한 파일의 동일한 파일 형식 삭제 4. 복사 첫 번째 방법 두 번째 사용 모듈 python 읽기와 쓰기, 복사 파일...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.