david-coder
2/10/2020 - 8:03 AM

File

文件处理的快速实现

public enum SystemDirectries
{
    DropApps = 0,
    ProgramFiles = 1,
    ProgramData = 3,
    AppData = 4
}

public class File
{

    public static string GetAssemblyDirectory(System.Reflection.Assembly assembly = null)
    {

        var asm = assembly != null
                  ? assembly
                  : System.Reflection.Assembly.GetExecutingAssembly();

        string dir = asm.CodeBase;

        if (dir.StartsWith("file:///", StringComparison.CurrentCultureIgnoreCase))
            dir = dir.Substring(8).Replace("/", "\\");
        dir = System.IO.Directory.GetParent(dir).FullName;

        return dir;

    }

    public static string GetTempFolder()
    {
        string folder = Environment.GetEnvironmentVariable("TEMP");
        if (System.IO.Directory.Exists(folder)) return folder;
        folder = System.IO.Path.GetTempPath();
        if (System.IO.Directory.Exists(folder)) return folder;
        folder = Environment.GetEnvironmentVariable("TMP");
        if (System.IO.Directory.Exists(folder)) return folder;
        folder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp");
        if (!System.IO.Directory.Exists(folder)) System.IO.Directory.CreateDirectory(folder);
        return folder;
    }

    public static string GetVersion(string filepath)
    {

        try
        {

            var obtype = Type.GetTypeFromProgID("Scripting.FileSystemObject");
            object word = Activator.CreateInstance(obtype);

            string version = obtype.InvokeMember("GetFileVersion", System.Reflection.BindingFlags.InvokeMethod, null, word, new object[] { filepath })?
                             .ToString()?.Trim();

            if (version?.Contains(".") == true) return version;

        }
        catch { }

        try
        {

            var info = System.Diagnostics.FileVersionInfo.GetVersionInfo(filepath);
            return info.FileVersion?.Trim() ?? string.Empty;

        }
        catch { }

        return string.Empty;

    }

    public static string GetMd5(string filepath)
    {

        try
        {

            byte[] bytes;
            using (var file = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                bytes = md5.ComputeHash(file);
            }

            var sb = new System.Text.StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append(bytes[i].ToString("x2"));
            }

            return sb.ToString();

        }
        catch (Exception)
        {
            return string.Empty;
        }

    }

    public static string GetFileType(string filepath)
    {
        return System.IO.Path.GetExtension(filepath)?.Replace(".", "").ToLower()
            ?? string.Empty;
    }

    public static string Space(long bytesLength)
    {
        double num;
        if (bytesLength < 0x400L)
        {
            return (bytesLength + "B");
        }
        if (bytesLength < 0x100000L)
        {
            num = ((double)bytesLength) / 1024.0;
            return (num.ToString("0.#") + "KB");
        }
        if (bytesLength < 0x40000000L)
        {
            num = (((double)bytesLength) / 1024.0) / 1024.0;
            return (num.ToString("0.#") + "MB");
        }
        if (bytesLength < 0x10000000000L)
        {
            num = ((((double)bytesLength) / 1024.0) / 1024.0) / 1024.0;
            return (num.ToString("0.#") + "GB");
        }
        return "非常大";
    }

    public static string GetFolder(SystemDirectries dir)
    {

        string folder = null;

        switch (dir)
        {
            case SystemDirectries.ProgramData:
                folder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                break;
            case SystemDirectries.AppData:
                folder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                break;
            case SystemDirectries.ProgramFiles:
                folder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
                if (!CheckCommonFolder(folder)) folder = GetProgramFolder();
                break;
            case SystemDirectries.DropApps:
                folder = System.IO.Path.Combine(
                    GetFolder(SystemDirectries.ProgramFiles),
                    "Workbase DropApps");
                break;
        }

        return folder;

    }

    public static bool CheckCommonFolder(string path)
    {
        path = path?.ToLower()?.Trim() ?? string.Empty;
        return !string.IsNullOrEmpty(path) && !path.Contains("system32") && !path.Contains("desktop") && !path.Contains("admin");
    }

    private static string GetProgramFolder()
    {

        string root = Environment.GetFolderPath(Environment.SpecialFolder.Windows).Substring(0, 3);

        var folders = new[]
        {
        System.IO.Path.Combine(root, "Program Files (x86)"),
        System.IO.Path.Combine(root, "Program Files"),
        System.IO.Path.Combine(root, "ProgramData")
    };

        foreach (string dir in folders)
        {
            if (System.IO.Directory.Exists(dir))
                return dir;
        }

        foreach (string dir in folders)
        {
            try
            {
                var info = System.IO.Directory.CreateDirectory(dir);
                if (info.Exists)
                    return dir;
            }
            catch (Exception) { }
        }

        return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

    }

    public static void ClearFiles(string folder, string pattern = "*", bool recur = false, bool recycle = false)
    {

        try
        {

            System.IO.Directory.GetFiles(folder, pattern).ToList()?
                .ForEach(f =>
                {
                    if (recycle)
                        DeleteFileObject(f);
                    else
                        System.IO.File.Delete(f);
                });

            if (recur)
            {
                string[] cfolders = System.IO.Directory.GetDirectories(folder);
                foreach (string cf in cfolders)
                {
                    DeleteFolder(cf, recycle);
                }
            }

        }
        catch (Exception) { }

    }

    public static void DeleteFolder(string folder, bool recycle = false)
    {
        try
        {
            if (recycle)
            {
                DeleteFileObject(folder);
            }
            else
            {
                ClearFiles(folder, recur: true);
                System.IO.Directory.Delete(folder);
            }
        }
        catch (Exception) { }
    }

    public static void CopyFolder(string from, string to)
    {

        if (!System.IO.Directory.Exists(to))
            System.IO.Directory.CreateDirectory(to);

        string[] files = System.IO.Directory.GetFiles(from);
        foreach (string f in files)
        {
            string newpath = System.IO.Path.Combine(to, System.IO.Path.GetFileName(f));
            System.IO.File.Copy(f, newpath);
        }

        string[] folders = System.IO.Directory.GetDirectories(from);
        foreach (string f in folders)
        {
            string newpath = System.IO.Path.Combine(to, System.IO.Path.GetFileName(f));
            CopyFolder(f, newpath);
        }

    }

    private const int FO_DELETE = 0x3;
    private const ushort FOF_NOCONFIRMATION = 0x10;
    private const ushort FOF_ALLOWUNDO = 0x40;
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    private class _SHFILEOPSTRUCT
    {
        public IntPtr hwnd;
        public UInt32 wFunc;
        public string pFrom;
        public string pTo;
        public UInt16 fFlags;
        public Int32 fAnyOperationsAborted;
        public IntPtr hNameMappings;
        public string lpszProgressTitle;
    }
    [DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern int SHFileOperation(_SHFILEOPSTRUCT str);
    public static void DeleteFileObject(string file)
    {
        var pm = new _SHFILEOPSTRUCT
        {
            pFrom = file + '\0',
            pTo = null,
            wFunc = FO_DELETE,
            fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION
        };
        SHFileOperation(pm);
    }

    public static byte[] GetEmbedResource(string rootNamespace, string folder, string filename)
    {
        string file = rootNamespace + "." + folder + "." + filename;
        return GetEmbedResource(file);
    }
    public static byte[] GetEmbedResource(string path)
    {

        var assembly = System.Reflection.Assembly.GetCallingAssembly();

        using (var sm = assembly.GetManifestResourceStream(path))
        {
            byte[] data = new byte[sm.Length];
            sm.Read(data, 0, data.Length);
            return data;
        }

    }

}