1
我有一個文本文件,文件中的值正在讀入應用程序(控制檯應用程序)。我想在文本文件中的值更改時更新應用程序中的值。我已經提到了這個link並做了一些修改。結果是當我更改文本文件中的值並嘗試保存它時,應用程序中的值不會更新,因爲文件無法保存。更改內容的監視文本文件可防止文件被寫入
如果我更改了文本文件中的值,如何更新應用程序中的值?
class Program
{
static void Main(string[] args)
{
TestClass sample = new TestClass();
sample.PropertyChanged += new PropertyChangedEventHandler(sample_PropertyChanged);
while (true)
{
using (StreamReader sr = new StreamReader("Testing.txt"))
{
// Read the stream to a string, and write the string to the console.
string str = sr.ReadToEnd();
sample.TestValue = str;
}
}
}
static void sample_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
TestClass sample = (TestClass)sender;
/*
* Use expression behind if you have more the one property instead sample.TestValue
* typeof(TestClass).GetProperty(e.PropertyName).GetValue(sample, null)*/
Console.WriteLine("Value of property {0} was changed! New value is {1}", e.PropertyName, sample.TestValue);
}
}
public class TestClass : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
string testValue = string.Empty;
public string TestValue
{
get { return testValue; }
set
{
testValue = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("TestValue"));
}
}
}
不確定循環是否導致此問題。你可以利用[FileSystemWatcher](https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher%28v=vs.110%29.aspx) – qxg
嗨@qxg,感謝您的評論。在實際環境中,文本文件中的值將是配置應用程序(連接到配置服務器)中的值,我可以從配置應用程序中檢索值,但無法更新我的應用程序中的值一旦價值改變了。對於上面的問題,我只是舉了一個類似於實際的簡單例子。 – YWah
你的代碼適合我。檢查其他問題。 – qxg