2013年9月4日 星期三

判斷文字檔是否被鎖住


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Threading;
namespace Ticket2
{
    public partial class FileWrite : System.Web.UI.Page
    {
        public static string cityPath = HttpContext.Current.Server.MapPath("~/city.txt");
        protected void Page_Load(object sender, EventArgs e)
        {
            FileInfo fi = new FileInfo(cityPath);
            if (IsFileLocked(fi))
            {
                Response.Write("目前檔案被鎖住");
            }
            else
            {
                StreamWriter sw = null;
                try
                {
                    //寫入文字檔
                    using (sw = new StreamWriter(cityPath, false, Encoding.UTF8))
                    {
                        for (int i = 1; i <= 500; i++)
                        {
                            sw.WriteLine("city" + i);
                            Thread.Sleep(10);
                        }
                    }
                }
                catch (Exception)
                {
                    sw.Close();
                }
                Response.Write("寫入完成");
            }
            fi = null;
        }
        //判斷檔案是否被鎖住
        protected virtual bool IsFileLocked(FileInfo file)
        {
            FileStream stream = null;
            try
            {
                if (file.Exists)
                {
                    stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                }
            }
            catch (IOException)
            {
                //檔案被鎖住
                return true;
            }
            finally
            {
                if (stream != null) { stream.Close(); }
            }
            return false;
        }
    }
}

沒有留言:

張貼留言