我正在从Internet上读取XML文件。我将它写入隔离存储,我喜欢在那之后阅读它。这是代码
IsolatedStorageFile isf=IsolatedStorageFile.GetUserStoreForApplication();
private void findNearestButton_Click(object sender, RoutedEventArgs e)
{
findCity(isf);
}
private void findCity(IsolatedStorageFile isf)
{
filePath = AppResource.exchangeOfficesFile;
if (!isf.FileExists(filePath.ToString()))
{
takeXMLOnLine(isf,filePath);
}
parseXMLfile(isf,filePath);
}
private void takeXMLOnLine(IsolatedStorageFile isf, string filePath)
{
System.Uri targetUri = new System.Uri(AppResource.exchangeOfficesURI);
WebClient client = new WebClient();
client.DownloadStringAsync(targetUri);
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
using (IsolatedStorageFileStream rawStream = isf.OpenFile(filePath, FileMode.Create))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter writer = XmlWriter.Create(rawStream, settings))
{
string xmlResponse = e.Result.ToString();
xmlResponse = xmlResponse.Replace("<", "<");
xmlResponse = xmlResponse.Replace(">", ">");
writer.WriteString(xmlResponse);
// Write the XML to the file.
writer.Flush();
}
}
}
private void parseXMLfile(IsolatedStorageFile isf, string filePath)
{
using (IsolatedStorageFileStream str = isf.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
StreamReader reader = new StreamReader(str);
string line;
while ((line = reader.ReadLine()) != null)
{
MessageBox.Show(line);
}
reader.Close();
}
}
当我运行代码时,我在此行上获取了不允许对IsolatedStoreageFileStream错误的操作
using (IsolatedStorageFileStream str = isf.OpenFile(filePath, FileMode.Open, FileAccess.Read))
有人能帮助我吗?
答案 0 :(得分:0)
尝试这样的事情:
using (IsolatedStorageFile rootStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(filePath,
System.IO.FileMode.Open, rootStore))
{
... whatever you do with the file goes here
}
}
答案 1 :(得分:0)
如果文件路径有子目录,请查看该目录是否存在。这可能会导致这个问题。
答案 2 :(得分:0)
尝试阅读时文件是否存在?看起来如果文件不存在,则启动下载过程(但不要等待完成),然后尝试阅读。
相反,像:
private void findCity(IsolatedStorageFile isf)
{
filePath = AppResource.exchangeOfficesFile;
if (!isf.FileExists(filePath.ToString()))
{
takeXMLOnLine(isf,filePath);
}
else
{
parseXMLfile(isf,filePath);
}
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
using (IsolatedStorageFileStream rawStream = isf.OpenFile(filePath, FileMode.Create))
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter writer = XmlWriter.Create(rawStream, settings))
{
string xmlResponse = e.Result.ToString();
xmlResponse = xmlResponse.Replace("<", "<");
xmlResponse = xmlResponse.Replace(">", ">");
writer.WriteString(xmlResponse);
// Write the XML to the file.
writer.Flush();
}
}
parseXMLfile(isf,filePath);
}