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