日期:2014-05-17  浏览次数:21136 次

C#文件操作类

?

using System;
using System.IO;
using System.Text;
using System.Data;
using System.Collections;
using System.Runtime.InteropServices;

namespace DbConvert
{

?? ?/**********************************************************************************
?? ?*?
?? ?* 功能说明:文件操作类
?? ?* 作者:
?? ?* 版本:
?? ?*?
?? ?* *******************************************************************************/

?? ?/// <summary>
?? ?/// 文件操作类
?? ?/// </summary>
?? ?public class FileObj : IDisposable
?? ?{
?? ? ? ?private bool _alreadyDispose = false;

?? ? ? ?private const long KB = 1024;
?? ? ? ?private const long MB = 1024 * KB;
?? ? ? ?private const long GB = 1024 * MB;
?? ? ? ?private static long FolderFileSize(string path)
?? ? ? ?{
?? ? ? ? ? ?long size = 0;
?? ? ? ? ? ?try
?? ? ? ? ? ?{
?? ? ? ? ? ? ? ?FileInfo[] files = (new DirectoryInfo(path)).GetFiles();
?? ? ? ? ? ? ? ?foreach (FileInfo file in files)
?? ? ? ? ? ? ? ?{
?? ? ? ? ? ? ? ? ? ?size += file.Length;
?? ? ? ? ? ? ? ?}
?? ? ? ? ? ?}
?? ? ? ? ? ?catch (Exception ex)
?? ? ? ? ? ?{
?? ? ? ? ? ? ? ?MessageBox.Show(ex.Message);
?? ? ? ? ? ?}
?? ? ? ? ? ?return size;
?? ? ? ?}

?? ? ? ?private static long FolderSize(string path)
?? ? ? ?{
?? ? ? ? ? ?long Fsize = 0;
?? ? ? ? ? ?try
?? ? ? ? ? ?{
?? ? ? ? ? ? ? ?Fsize = FolderFileSize(path);
?? ? ? ? ? ? ? ?DirectoryInfo[] folders = (new DirectoryInfo(path)).GetDirectories();
?? ? ? ? ? ? ? ?foreach (DirectoryInfo folder in folders)
?? ? ? ? ? ? ? ? ? ?Fsize += FolderSize(folder.FullName);
?? ? ? ? ? ?}
?? ? ? ? ? ?catch (Exception ex)
?? ? ? ? ? ?{
?? ? ? ? ? ? ? ?MessageBox.Show(ex.Message);
?? ? ? ? ? ?}
?? ? ? ? ? ?return Fsize;
?? ? ? ?}

?? ? ? ?#region 构造函数
?? ? ? ?public FileObj()
?? ? ? ?{
?? ? ? ? ? ?//
?? ? ? ? ? ?// TODO: 在此处添加构造函数逻辑
?? ? ? ? ? ?//
?? ? ? ?}
?? ? ? ?~FileObj()
?? ? ? ?{
?? ? ? ? ? ?Dispose(); ;
?? ? ? ?}

?? ? ? ?protected virtual void Dispose(bool isDisposing)
?? ? ? ?{
?? ? ? ? ? ?if (_alreadyDispose) return;
?? ? ? ? ? ?//if (isDisposing)
?? ? ? ? ? ?//{
?? ? ? ? ? ?// ? ? if (xml != null)
?? ? ? ? ? ?// ? ? {
?? ? ? ? ? ?// ? ? ? ? xml = null;
?? ? ? ? ? ?// ? ? }
?? ? ? ? ? ?//}
?? ? ? ? ? ?_alreadyDispose = true;
?? ? ? ?}
?? ? ? ?#endregion

?? ? ? ?#region IDisposable 成员
?? ? ? ?[DllImport("kernel32")]
?? ? ? ?private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
?? ? ? ?[DllImport("kernel32")]//返回表示失败,非为成功
?? ? ? ?private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
?? ? ? ?public void Dispose()
?? ? ? ?{
?? ? ? ? ? ?Dispose(true);
?? ? ? ? ? ?GC.SuppressFinalize(this);
?? ? ? ?}

?? ? ? ?#endregion

?? ? ? ?#region 取得文件后缀名
?? ? ? ?/****************************************