這裏可能是一個非常簡單的noob問題。基本上我有一個txt文件,它有許多控制我寫的服務的變量。目前在每個需要一個變量的void中,我打開文件,讀取文件,選擇行並使用變量。從一個公共區域獲取變量到另一個
我的問題是,是否有一種方法來全局分配變量。這樣我所有的空洞都可以使用它們。這樣,我只需要在讀取所有內容後打開文件,將所有內容分配給一個變量。而不是我現在正在做的那種方式,我多次打開文件,在多數情況下尋找相同的變量。
我編輯了我的問題,並添加了一些代碼以嘗試更好地解釋。 所以下面我有2個空隙。他們都打開相同的文件,但在文件中查找不同的行。我想知道是否可以創建一個讀取整個文件的「全局」變量列表,然後我可以調用我需要的變量,而不必每次打開文件都需要信息。
public void day_timer()
{
string temptimer = "";
string timeloop = "";
using (var streamReader = System.IO.File.OpenText(@"C:\somefile"))
{
var lines = streamReader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
if (line.Contains("Day_Time:"))
{
temptimer = line;
continue;
}
}
}
timeloop = temptimer.Remove(0, 9);
int inter = Convert.ToInt32(timeloop);
System.Timers.Timer timer1 = new System.Timers.Timer();
InitializeComponent();
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Interval = inter * 1000 * 60;
timer1.Enabled = true;
timer1.Start();
error_handling("backup started " + DateTime.Now + ". Incremental Backup set to every " + timeloop + " Minutes", "Incbackuplog.txt");
}
//Incrememtal Backup Timer
public void inc_timer()
{
string temptimer = "";
string timeloop = "";
using (var streamReader = System.IO.File.OpenText(@"C:\somefile"))
{
var lines = streamReader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
if (line.Contains("Inc_interval:"))
{
temptimer = line;
continue;
}
}
}
timeloop = temptimer.Remove(0, 13);
int inter = Convert.ToInt32(timeloop);
System.Timers.Timer timer1 = new System.Timers.Timer();
InitializeComponent();
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Interval = inter * 1000 * 60;
timer1.Enabled = true;
timer1.Start();
error_handling(" Backup Started "+DateTime.Now+". Incremental Backup set to every "+timeloop+" Minutes", "Incbackuplog.txt");
}
有很多方法可以做到這一點,很難推薦沒有一些代碼或更多信息的路徑。 –
是的。你有什麼特別的問題?發佈您的當前代碼可能會有幫助,因爲它可能會突出顯示阻止您的內容。但是你似乎明白你的描述需要做什麼,那麼問題是什麼? –
如果你正在尋找建議,那麼如果我要實現這樣的功能,我會創建一個類,該屬性與來自文本文件的變量相匹配,並且有一些像'bool isFileRead'這樣的標誌。然後,當我想使用某個變量時,我首先檢查標誌 - 如果'isFileRead'等於false,我將讀取文本文件並賦值,否則它已經被讀取並使用類屬性。 – Leron