2013-07-25 51 views
0

這是代碼:如何檢查文件大小是否大於開始?

private void timer2_Tick(object sender, EventArgs e) 
     { 
      timerCount += 1; 
      TimerCount.Text = TimeSpan.FromSeconds(timerCount).ToString(); 
      TimerCount.Visible = true; 
      if (File.Exists(Path.Combine(contentDirectory, "msinfo.nfo"))) 
      { 
       string fileName = Path.Combine(contentDirectory, "msinfo.nfo"); 
       FileInfo f = new FileInfo(fileName); 
       long s1 = f.Length; 
       if (f.Length > s1) 
       { 
        timer2.Enabled = false; 
        timer1.Enabled = true; 
       } 
      } 
     } 

一旦該文件是存在的大約1.5MB大小 但幾分鐘後,該文件被更新到幾乎23MB。 所以我想檢查一下,如果文件大一些,那麼在停止timer2並啓動timer1之前它是什麼。

但是這一行:if(f.Length> s1)不合邏輯,因爲我一直在做long s1 = f.Length;

如何檢查文件是否大於那是什麼?

+0

也許有另一種方式來做到這一點。問題在於文件存在,但隨後在幾分鐘後用後臺程序進行更新。我的程序使用backgroundworker,但問題是它沒有檢測到後臺程序繼續工作(msinfo32.exe),並在幾分鐘後更新文件。 – DanielVest

+0

查看此方法:[http://stackoverflow.com/a/15024737/674700](http://stackoverflow.com/a/15024737/674700)。 –

回答

1

您可以依賴一個全局變量(例如您用於contentDirectory的變量)來存儲上次觀察的大小。示例代碼:

public partial class Form1 : Form 
{ 
    long timerCount = 0; 
    string contentDirectory = "my directory"; 
    long lastSize = 0; 
    double biggerThanRatio = 1.25; 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void timer2_Tick(object sender, EventArgs e) 
    { 
     timerCount += 1; 
     TimerCount.Text = TimeSpan.FromSeconds(timerCount).ToString(); 
     TimerCount.Visible = true; 
     if (File.Exists(Path.Combine(contentDirectory, "msinfo.nfo"))) 
     { 
      string fileName = Path.Combine(contentDirectory, "msinfo.nfo"); 
      FileInfo f = new FileInfo(fileName); 
      if (f.Length >= biggerThanRatio * lastSize && lastSize > 0) 
      { 
       timer2.Enabled = false; 
       timer1.Enabled = true; 
      } 

      lastSize = f.Length; 
     } 
    } 
} 
相關問題