【发布时间】:2015-11-05 05:50:02
【问题描述】:
我有一个文本文件,并且正在将文件中的值读入应用程序(控制台应用程序)。当文本文件中的值发生更改时,我想更新应用程序中的值。我参考了这个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
-
嗨@qxg,感谢您的评论。在实际环境中,文本文件中的值将是配置应用程序中的值(连接到配置服务器),我可以从配置应用程序中检索值,但无法更新我的应用程序中的值一旦值改变。对于上面的问题,我只是举了一个与实际类似的简单例子。
-
您的代码对我有用。检查其他问题。
-
运行我的应用程序后,值一直在循环,当我更改文本文件中的值时,它不允许我保存,因为该文件已被另一个程序使用。
-
那只是文件系统的问题?所以问题不在于如何实现
INotifyPropertyChanged(当然,最好通过比较TestValue属性中的旧值来检查值是否真的改变了)。您对如何从另一个应用程序/服务器读取值有疑问。如果可能,请更新问题。
标签: c# console-application updates inotifypropertychanged