c#文件圖片操做

系統特殊目錄路徑

//取得特殊文件夾的絕對路徑
//桌面
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//收藏夾
Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
//個人文檔
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//最近使用的文檔
Environment.GetFolderPath(Environment.SpecialFolder.Recent);

文件操做

void CheckFileExists() 
{
    //經過函數File.Exists方法判斷文件是否存在
    //string fileName = @"C:\Dell\demo.txt";
    //if (File.Exists(fileName))
    //{
    //    Console.WriteLine("File {0} exists.", fileName);
    //}
    string fileName = @"C:\Dell\demo.txt";
    if (File.Exists(fileName))
                    this.tbInfo.AppendText(fileName + "存在\r\n"); else
                    this.tbInfo.AppendText(fileName + "不存在\r\n");
}
void GetFileInfo() 
{
    //經過FileInfo取得文件屬性
    string fileName = this.tbFile.Text;
    FileInfo info = new FileInfo(fileName);
    // 判斷文件是否存在
    this.tbInfo.AppendText("文件是否存在:" + info.Exists.ToString() + "\r\n");
    // 獲取文件名
    this.tbInfo.AppendText("文件名:" + info.Name + "\r\n");
    // 獲取文件擴展名
    this.tbInfo.AppendText("擴展名:" + info.Extension + "\r\n");
    // 獲取文件躲在文件夾
    this.tbInfo.AppendText("所在文件夾:" + info.Directory.Name + "\r\n");
    // 獲取文件長度
    this.tbInfo.AppendText("文件長度:" + info.Length + "\r\n");
    // 獲取或設置文件是否只讀
    this.tbInfo.AppendText("是否只讀:" + info.IsReadOnly + "\r\n");
    // 獲取或設置文件建立時間
    this.tbInfo.AppendText("建立時間:" + info.CreationTime + "\r\n");
    // 獲取或設置文件最後一次訪問時間
    this.tbInfo.AppendText("最後一次訪問時間:" + info.LastAccessTime + "\r\n");
    // 獲取或設置文件最後一次寫入時間
    this.tbInfo.AppendText("最後一次寫入時間:" + info.LastWriteTime + "\r\n");
}
void CopyFile() 
{
    // 複製文件
    // 原文件
    string sourceFileName = @"C:\Users\Dell\Desktop\timer.png";
    // 新文件
    string destFileName = @"e:\timer.png";
    File.Copy(sourceFileName, destFileName);
}
void MoveFile() 
{
    // 移動文件,能夠跨卷標移動
    // 文件移動後原文件被刪除
    string sourceFileName = @"C:\Users\Dell\Desktop\timer.png";
    string destFileName = @"e:\timer.png";
    File.Move(sourceFileName, destFileName);
}
void DeleteFile() 
{
    //刪除指定文件
    string fileName = @"C:\Dell\demo.txt";
    // 刪除前需檢查文件是否存在
    if (File.Exists(fileName))
                    File.Delete(fileName);
}
void PickFile() 
{
    //從工具箱拖入OpenFileDialog控件命名爲ofd,或者直接定義
    OpenFileDialog ofd = new OpenFileDialog();
    // 當所選文件不存在時給出警告提示
    ofd.CheckFileExists = true;
    // 是否添加默認文件擴展名
    ofd.AddExtension = true;
    // 設置默認擴展文件名
    ofd.DefaultExt = ".txt";
    // 設置文件類型篩選規則,
    // 組與組之間用「|」分隔,每組中文件類型與擴展名用「|」分割,多個文件類型用「;」分隔
    ofd.Filter = "文本文件|*.txt|圖片文件|*.png;*gif;*.jpg;*.jpeg;*.bmp";
    // 設置是否支持多選
    ofd.Multiselect = true;
    // 設置對話框標題
    ofd.Title = "選擇文件:";
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    {
        this.tbFile.Text = ofd.FileName;
        // 依次列出多選的文件名稱
        foreach (string fname in ofd.FileNames) 
        {
            this.tbInfo.AppendText(fname + "\r\n");
        }
    }
}
void RenameFile() 
{
    // 使用VB方法,重命名文件
    Computer myPC = new Computer();
    string sourceFileName = @"C:\Users\Dai\Desktop\截圖\timer.png";
    string newFileName = @"timer12.png";
    //必須是名稱,而不是絕對路徑
    myPC.FileSystem.RenameFile(sourceFileName, newFileName);
    myPC = null;
}
View Code

 

文件夾操做

#region 文件夾操做
/// <summary>
/// 選擇路徑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOpenDir_Click(object sender, EventArgs e) 
{
    // 從工具箱拖入一個FolderBrowserDialog,命名爲fbd。除了拖入,還可直接定義
    FolderBrowserDialog fbd = new FolderBrowserDialog();
    // 設置文件夾選擇框提示文本
    fbd.Description = "請選擇一個文件夾:";
    // 設置默認位置爲桌面
    fbd.RootFolder = Environment.SpecialFolder.DesktopDirectory;
    // 設置是否顯示「新建文件夾」按鈕
    fbd.ShowNewFolderButton = false;
    // 設置默認選中的文件夾爲本地目錄
    fbd.SelectedPath = @"e:\";
    // 設置默認選中的文件夾爲網絡路徑
    //this.fbd.SelectedPath = @"\\192.168.1.1\";
    // 顯示對話框,並返回已選中的文件夾
    if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    {
        this.tbDir.Text = fbd.SelectedPath;
    }
}
/// <summary>
/// 文件夾屬性
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetDirInfo_Click(object sender, EventArgs e) 
{
    string dirName = this.tbDir.Text;
    if (string.IsNullOrEmpty(dirName)) 
    {
        this.tbInfo.AppendText("文件夾不能空\r\n");
        return;
    }
    // 檢查文件夾是否存在
    if (Directory.Exists(dirName)) 
    {
        // 根據路徑得到文件夾屬性
        DirectoryInfo info = new DirectoryInfo(dirName);
        this.tbInfo.AppendText(string.Format("完整路徑:{0}\r\n", info.FullName));
        this.tbInfo.AppendText(string.Format("獲取目錄的根:{0}\r\n", info.Root));
        this.tbInfo.AppendText(string.Format("獲取目錄的父目錄:{0}\r\n", info.Parent));
        this.tbInfo.AppendText(string.Format("建立時間:{0}\r\n", info.CreationTime));
        this.tbInfo.AppendText(string.Format("最後一次訪問時間:{0}\r\n", info.LastAccessTime));
        this.tbInfo.AppendText(string.Format("最後一次寫入時間:{0}\r\n", info.LastWriteTime));
    } else 
    {
        this.tbInfo.AppendText(string.Format("文件夾不存在{0}\r\n", dirName));
    }
}
/// <summary>
/// 文件夾權限
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetDirSec_Click(object sender, EventArgs e) 
{
    //取得文件夾的訪問權限
    string dirName = this.tbDir.Text;
    if (string.IsNullOrEmpty(dirName)) 
    {
        this.tbInfo.AppendText("文件夾不能空\r\n");
        return;
    }
    DirectoryInfo dirInfo = new DirectoryInfo(dirName);
    // 需引用命名空間System.Security.AccessControl;
    // 取得訪問控制列表ACL信息
    DirectorySecurity sec = dirInfo.GetAccessControl(AccessControlSections.Access);
    foreach (FileSystemAccessRule rule in 
            sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) 
    {
        // 文件夾名稱
        tbInfo.AppendText(dirName + "\t");
        // 取得Windows帳號或sid
        tbInfo.AppendText(rule.IdentityReference.Value + "\t");
        // 取得文件夾權限
        tbInfo.AppendText(rule.FileSystemRights.ToString() + "\r\n");
    }
}
/// <summary>
/// 遍歷子文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetDirFiles_Click(object sender, EventArgs e) 
{
    string dirName = this.tbDir.Text;
    if (string.IsNullOrEmpty(dirName)) 
    {
        this.tbInfo.AppendText("文件夾不能空\r\n");
        return;
    }
    //遍歷文件夾中的文件
    DirectoryInfo info = new DirectoryInfo(dirName);
    foreach (FileInfo fInfo in info.GetFiles()) 
    {
        this.tbInfo.AppendText(fInfo.FullName + "\r\n");
    }
}
/// <summary>
/// 遍歷子文件夾
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetSubDir_Click(object sender, EventArgs e) 
{
    string dirName = this.tbDir.Text;
    if (string.IsNullOrEmpty(dirName)) 
    {
        this.tbInfo.AppendText("文件夾不能空\r\n");
        return;
    }
    //遍歷文件夾中的子文件夾
    DirectoryInfo info = new DirectoryInfo(dirName);
    foreach (DirectoryInfo dInfo in info.GetDirectories()) 
    {
        this.tbInfo.AppendText(dInfo.FullName + "\r\n");
    }
}
/// <summary>
/// 遍歷所有子文件夾
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetAllSubDir_Click(object sender, EventArgs e) 
{
    string dirName = this.tbDir.Text;
    if (string.IsNullOrEmpty(dirName)) 
    {
        this.tbInfo.AppendText("文件夾不能空\r\n");
        return;
    }
    //使用遞歸方法遍歷文件夾中全部的子文件夾
    DirectoryInfo info = new DirectoryInfo(dirName);
    foreach (DirectoryInfo dInfo in info.GetDirectories()) 
    {
        //ReadDirs(dInfo.FullName);
        ReadDirs(dInfo.FullName,0);
        this.tbInfo.AppendText(dInfo.FullName + "\r\n");
    }
}
private void ReadDirs(string dirName) 
{
    // 遞歸讀取子文件夾
    DirectoryInfo info = new DirectoryInfo(dirName);
    foreach (DirectoryInfo dInfo in info.GetDirectories()) 
    {
        ReadDirs(dInfo.FullName);
        this.tbInfo.AppendText(dInfo.FullName + "\r\n");
    }
}
private void ReadDirs(string dirName, int level) 
{
    // 記錄文件夾讀取深度
    level++;
    // 當遍歷深度小於設定值時才繼續讀取
    if (level < totalLevel) 
    {
        DirectoryInfo info = new DirectoryInfo(dirName);
        #region 顯示文件信息
                        foreach (FileInfo fInfo in info.GetFiles()) 
        {
            this.tbInfo.AppendText(fInfo.FullName + "\r\n");
        }
        #endregion
                #region 顯示子文件夾
                        foreach (DirectoryInfo dInfo in info.GetDirectories()) 
        {
            ReadDirs(dInfo.FullName, level);
            this.tbInfo.AppendText(dInfo.FullName + "\r\n");
        }
        #endregion
    }
}
/// <summary>
/// 刪除文件夾
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeleteDir_Click(object sender, EventArgs e) 
{
    string dirName = this.tbDir.Text;
    if (string.IsNullOrEmpty(dirName)) 
    {
        this.tbInfo.AppendText("文件夾不能空\r\n");
        return;
    }
    if (Directory.Exists(dirName)) 
    {
        if(MessageBox.Show("您肯定要刪除指定文件夾嗎?","確認框",
                    MessageBoxButtons.YesNo,MessageBoxIcon.Question)
                    == System.Windows.Forms.DialogResult.Yes) 
        {
            Directory.Delete(dirName);
        }
    }
}
/// <summary>
/// 移動文件夾
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMoveDir_Click(object sender, EventArgs e) 
{
    string dirName = this.tbDir.Text;
    if (string.IsNullOrEmpty(dirName)) 
    {
        this.tbInfo.AppendText("文件夾不能空\r\n");
        return;
    }
    if (Directory.Exists(dirName)) 
    {
        if (MessageBox.Show("您肯定要移動文件夾嗎?", "確認框", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == System.Windows.Forms.DialogResult.Yes) 
        {
            //源路徑和目標路徑必須具備相同的根。移動操做在卷之間無效
            Directory.Move(dirName, @"C:\Users\Dai\Desktop\截圖222");
        }
    }
}
/// <summary>
/// 建立文件夾
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreateDir_Click(object sender, EventArgs e) 
{
    // appPath = System.Windows.Forms.Application.StartupPath + "\\";
    string dirName = appPath + DateTime.Now.ToString("yyyyMMddHHmmss");
    Directory.CreateDirectory(dirName);
    this.tbInfo.AppendText(string.Format("當前工做目錄:{0}\r\n", Directory.GetCurrentDirectory()));
    Directory.SetCurrentDirectory(@"c:\");
    Directory.CreateDirectory(DateTime.Now.ToString("yyyyMMddHHmmss"));
    this.tbInfo.AppendText(string.Format("已建立文件夾{0}\r\n", dirName));
}
/// <summary>
/// 特殊文件夾路徑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnFolderPath_Click(object sender, EventArgs e) 
{
    //取得特殊文件夾的絕對路徑
    this.tbInfo.AppendText(string.Format("特殊文件夾路徑\r\n桌面:{0}\r\n", Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
    this.tbInfo.AppendText(string.Format("收藏夾:{0}\r\n", Environment.GetFolderPath(Environment.SpecialFolder.Favorites)));
    this.tbInfo.AppendText(string.Format("個人文檔:{0}\r\n", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)));
    this.tbInfo.AppendText(string.Format("最近使用的文檔:{0}\r\n", Environment.GetFolderPath(Environment.SpecialFolder.Recent)));
    //取得特殊文件夾的絕對路徑
    //桌面
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    //收藏夾
    Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
    //個人文檔
    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    //最近使用的文檔
    Environment.GetFolderPath(Environment.SpecialFolder.Recent);
}
/// <summary>
/// 重命名
/// </summary>
void RenameDirectory() 
{
    // 重命名文件夾
    Computer myPC = new Computer();
    string sourceDirName = @"C:\Users\Dell\Desktop\截圖";
    string newDirName = @"截圖";
    //必須是名稱,而不是絕對路徑
    myPC.FileSystem.RenameDirectory(sourceDirName, newDirName);
    myPC = null;
}
private void btnRenameDir_Click(object sender, EventArgs e) 
{
    RenameDirectory();
}
View Code

 

文件讀寫

讀取文件

FileStream

try 
{
    // 以只讀模式打開文本文件
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) 
    {
        byte[] bytes = new byte[fs.Length];
        int numBytesToRead = (int)fs.Length;
        int numBytesRead = 0;
        while (numBytesToRead > 0) 
        {
            int n = fs.Read(bytes, numBytesRead, numBytesToRead);
            if (n == 0)
                            break;
            numBytesRead += n;
            numBytesToRead -= n;
        }
        numBytesToRead = bytes.Length;
        // 以UTF-8編碼解碼
        //string content = Encoding.UTF8.GetString(bytes);
        // 以GBK方式讀取
        string content = Encoding.GetEncoding("GBK").GetString(bytes);
        fs.Close();
        MessageBox.Show(content);
    }
}
catch (System.IO.FileNotFoundException ioex) 
{
    MessageBox.Show("文件不存在","錯誤",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
catch (Exception ex) 
{
    MessageBox.Show("其餘錯誤", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally 
{
}
View Code

StreamReader

StreamReader sr = new StreamReader(fileName, Encoding.UTF8);
string line;
// 逐行讀取
while ((line = sr.ReadLine()) != null)
{
    Console.WriteLine(line.ToString());
}
sr.Close();
View Code

ReadAllText

if (System.IO.File.Exists(fileName))
{
    // 默認以UTF-8編碼讀取
    //string content = System.IO.File.ReadAllText(fileName);
    // 以漢字GBK編碼讀取
    string content = System.IO.File.ReadAllText(fileName,Encoding.GetEncoding("GBK"));
    MessageBox.Show(content);
}
View Code

ReadAllLines

// 讀取全部行
foreach (var line in File.ReadAllLines(fileName))
{
    Console.WriteLine(line);
}
View Code

寫入文件

FileStream

// 以追加模式打開文件,當文件不存在時建立它
using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write))
{
    string content = "跟我一塊兒作項目";
    // 以UTF-8編碼寫入
    //fs.Write(Encoding.UTF8.GetBytes(content), 0, Encoding.UTF8.GetByteCount(content));
    // 以GBK編碼寫入
    fs.Write(Encoding.GetEncoding("GBK").GetBytes(content), 0, 
        Encoding.GetEncoding("GBK").GetByteCount(content));
    fs.Close();
    MessageBox.Show("已寫入");
}
View Code

StreamWriter

StreamWriter sw = File.AppendText(fileName);
//開始寫入
sw.Write("跟我一塊兒作項目\r\n");
//清空緩衝區
sw.Flush();
//關閉流
sw.Close();
View Code

AppendAllText

// 若是文件存在則追加文本
// 若是文件不存在則建立文件,並寫入文本
// 默認以UTF-8編碼寫入
//File.AppendAllText(fileName, "追加文本\r\n",Encoding.UTF8);
// 若是字符集選擇了ASCII,那麼寫入的漢字將編程亂碼
//File.AppendAllText(fileName, "追加文本\r\n", Encoding.ASCII);
// 以GBK編碼寫入
File.AppendAllText(fileName, "追加文本\r\n", Encoding.GetEncoding("GBK"));
View Code

 

圖像操做

圖片打水印

private void btnWrite_Click(object sender, EventArgs e)
{
    // 從圖片文件建立一個Image對象
    Image img = System.Drawing.Image.FromFile(imgName);
    // 建立一個Bitmap對象
    Bitmap bmp = new Bitmap(img);
    // 及時銷燬img
    img.Dispose();
    // 從bpm建立一個Graphics對象
    Graphics graphics = Graphics.FromImage(bmp);
    // 指定在縮放或旋轉圖像時使用的算法
    // 使用高質量的雙線性插值法。執行預篩選以確保高質量的收縮。
    // 需引用System.Drawing.Drawing2D
    graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
    // 定義單色畫筆,用於填充圖形形狀,如矩形、橢圓、扇形、多邊形和封閉路徑。
    SolidBrush brush = new SolidBrush(Color.Red);
    // 定義起始位置
    PointF P = new PointF(250, 300);
    // 定義字體
    Font font = new Font("微軟雅黑", 40);
    // 繪製字符
    graphics.DrawString("這是繪製的文字", font, brush, P);
    // 以jpeg格式保存圖像文件
    // System.Drawing.Imaging
    //bmp.Save(newImgName,ImageFormat.Jpeg);
    bmp.Save(newImgName, ImageFormat.Gif);
    // 銷燬對象
    font.Dispose();
    graphics.Dispose();
    img.Dispose();
    this.pictureBox1.Image = bmp;
}
View Code

修改圖片格式

private void btnSaveAs_Click(object sender, EventArgs e)
{
    string imgName = appPath + "Penguins.jpg";
    Image img = System.Drawing.Image.FromFile(imgName);
    // 建立一個Bitmap對象
    Bitmap bmp = new Bitmap(img);
    // 另存爲gif格式
    bmp.Save(appPath + "Penguins_new.gif", ImageFormat.Gif);
    // 另存爲png格式
    bmp.Save(appPath + "Penguins_new.png", ImageFormat.Png);
    // 另存爲bmp格式
    bmp.Save(appPath + "Penguins_new.bmp", ImageFormat.Bmp);
    // 銷燬對象
    img.Dispose();
}
View Code

建立縮略圖

private void btnThumbnail_Click(object sender, EventArgs e)
{
    // 從圖片文件建立image對象
    Image img = Image.FromFile(imgName);
    // 建立縮略圖,指定寬度和長度
    // 提供一個回調方法,用於肯定 GetThumbnailImage 方法應在什麼時候提早取消執行
    Image thumbnailImage = img.GetThumbnailImage(100, 100, 
        new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
    thumbnailImage.Save(appPath + "Penguins_thum.jpg", ImageFormat.Jpeg);
    thumbnailImage.Dispose();
    img.Dispose();
}
View Code
相關文章
相關標籤/搜索