解决文件读取问题 [英] resolve file reading issues

查看:70
本文介绍了解决文件读取问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#下载2个xml文件:



I am using C# to download 2 xml files:

using (FileStream fs = new FileStream(Path.Combine(Properties.Settings.Default.XmlLocation, DateTime.Now.ToString("yyyyMMddHHmm") + " File2.xml"), FileMode.Create))
               {
                   "\n");
                   client2.DownloadFile(location);
                   Program.processLog.Write("XML File 2 Retrieved");
                   fs.Close();
               }





我然后按如下方式解析XML文件:







I then parse the XML file as follows:


XmlSerializer deserializer = new XmlSerializer(typeof(DOGS), new XmlRootAttribute("DOGS"));
                   using (XmlReader reader = XmlReader.Create(Path.Combine(Properties.Settings.Default.XmlLocation, DateTime.Now.ToString("yyyyMMddHHmm") + " File2.xml")))
                   {

                       xmlReadFileOne = (DOGS)deserializer.Deserialize(reader);
                       Program.processLog.Write("File 1 Successfully Deserialized");
                       return xmlReadFileOne;  
                   }







我遇到的问题是:



如果我在15:26从服务器检索XML文件



如果我在15岁时尝试读取相同的XML文件:27



我收到错误,因为时间不匹配,文件不存在。



我认为这是因为当我使用XML阅读器阅读文件时,我正在使用XMLReader.create,当我想要它的所有内容时,或许读取文件?我不确定?



同样在目录中有大量的XML文件,因为我每5分钟下载一个文件,所以我需要确保我读了最新的反序列化时的XML文件。



请帮我解决这个问题?




The problem I am having is:

If I retrieve the XML file from the server at 15:26

If I then try and read the same XML file at 15:27

I receive an error that file does not exist because the times do not match.

I think its because when I am reading the file with XML reader I am using XMLReader.create, when all I want to do it read the file perhaps? I am not sure??

Also in the directory there are loads of XML files as I download a file every 5 mins, so I need to ensure I read the latest XML file when deserializing.

Please can you help me resolve this?

推荐答案

简单的答案是:永远不要检索时间两次,如果你需要再次使用它:它可能会改变!



所以存储它 - 甚至存储文件名 - 正如我在回答你上一个问题时所做的那样:

The simple answer is: never retrieve the time twice if you need to use it again: it may well change!

So store it - or even store the filename - as I did in my answer to your previous question:
string fileName = @"D:\MyFolder\" + DateTime.Now.ToString("yyyyMMddHHmmss") + " Dogs.xml";



然后你知道你正在访问同一个文件。

如果你用不同的方法做这个,你不能把它从一个传递到另一个,然后找到最新版本 - 这只是我之前给你的代码的一个变化:


You then know you are accessing the same file.
If you are doing this in different methods, and you can't pass it from one to the other, then find the latest version - it's just a change on the code I gave you before:

string latest = Directory.GetFiles(@"D:\MyFolder", "* Dogs.xml")
                    .Select(s => new FileInfo(s))
                    .OrderByDescending(fi => fi.CreationTime)
                    .Select(fi => fi.FullName)
                    .FirstOrDefault();


这篇关于解决文件读取问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆