1

我将 xml 文件从 Internet 下载到内存手机。我想查看 Internet 连接是否可用于进行下载,如果没有则发送消息。如果不是,我想查看内存中是否已经存在 xml 文件。如果存在,则应用程序不会进行下载。

问题是我不知道如何制作“if”条件来查看文件是否存在。

我有这个代码:

public MainPage()
{
    public MainPage()
    {
        if (NetworkInterface.GetIsNetworkAvailable())
        {
            InitializeComponent();

            WebClient downloader = new WebClient();
            Uri xmlUri = new Uri("http://dl.dropbox.com/u/32613258/file_xml.xml", UriKind.Absolute);
            downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Downloaded);
            downloader.DownloadStringAsync(xmlUri);
        }
        else
        {
            MessageBox.Show("The internet connection is not available");
        }
    }

    void Downloaded(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Result == null || e.Error != null)
        {
            MessageBox.Show("There was an error downloading the xml-file");
        }
        else
        {
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            var stream = new IsolatedStorageFileStream("xml_file.xml", FileMode.Create, FileAccess.Write, myIsolatedStorage);
            using (StreamWriter writeFile = new StreamWriter(stream))
            {
                string xml_file = e.Result.ToString();
                writeFile.WriteLine(xml_file);
                writeFile.Close();
            }
        }
    }
}

我不知道如何查看文件是否存在条件:(

4

1 回答 1

5

IsolatedStorageFile 类有一个名为FileExists. 请参阅此处的文档 如果您只想检查文件名,也可以使用GetFileNames为您提供隔离存储根目录中文件的文件名列表的方法。文档在这里。

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if(myIsolatedStorage.FileExists("yourxmlfile.xml))
{
    // do this
}
else
{
    // do that
}

或者

IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileNames = myIsolatedStorage.GetFileNames("*.xml")
foreach (string fileName in fileNames)
{
    if(fileName == "yourxmlfile.xml")
    {
      // do this
    }
    else
    {
      // do that
    }
}

I will not guarantee that the above code will work exactly, but this is the general idea of how to go about it.

于 2011-10-31T11:01:27.837 回答