c# - 用于打开文件的 WPF 命令行参数给出无限循环

标签 c# command-line-arguments infinite-loop vcf-vcard

这真是一个奇怪的事情!我正在开发一个读取 vCard 文件的应用程序,其中包含一个人的联系方式等信息。每个文件可能包含单独的“部分”,每个部分包含一个人的详细信息,这些详细信息由 BEGIN:VCARD [此处的数据] END:VCARD 分隔。

为了使我的用户能够查看所有不同的详细信息,我允许我的程序使用详细信息填充应用程序中的文本框,然后打开一个新窗口并使用该窗口执行此操作,但对于每个不同的文件中的部分。

当在资源管理器中双击 vCard 文件而打开我的程序时,就会出现问题。它不断循环浏览 vCard。我不知道该怎么办,但下面是我有问题的代码:

    public void readVcard(string fname)//Reads vCard and then loops through sections
    {
        try
        {
            using (StreamReader r = new StreamReader(fname))
            {
                string input = File.ReadAllText(fname);//read through file

                String[] vArray = input.Split(new string[] { "BEGIN:VCARD" }, StringSplitOptions.None);

                int i;

                for (i = 1; i < vArray.Length; i++)
                {
                    MainWindow a = new MainWindow();
                    a.parser(vArray[i]); //Parser is the function that populates the app
                    a.Show();
                }

                return;
            }
        }...

从这里调用此函数:

    void MainWindow_Loaded(object sender, RoutedEventArgs e)//Processes a file when opened externally
    {
        if (Application.Current.Properties["ArbitraryArgName"] != null)
        {
            string fname = Application.Current.Properties["ArbitraryArgName"].ToString();

            readVcard(fname);

        }
    }

如果有人能提供帮助,我们将不胜感激。

最佳答案

我认为 Artyom 走在正确的道路上。

每次您创建另一个MainWindow并加载它时,您都会获得当前应用程序参数并跳回到readVcard,它将处理与您相同的vCard已经在处理并打开另一个MainWindow,它将继续该过程。

考虑将 MainWindow_Loaded() 中的所有代码移至应用程序的 Startup 事件中。这样,它只会在程序首次加载时被调用一次,而不是每次创建新窗口时被调用。

为此,您需要在 App.xaml 文件中注册该事件,如下所示:

<Application x:Class="MyProgram.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Startup="Application_Startup">
</Application>

然后在 App.xaml 后面的代码中放置用于读取 vCard 的代码。像这样:

namespace MyProgram
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (Application.Current.Properties["ArbitraryArgName"] != null)
            {
                string fname = Application.Current.Properties["ArbitraryArgName"].ToString();

                readVcard(fname);

            }
        }
    }
}

关于c# - 用于打开文件的 WPF 命令行参数给出无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5205986/

相关文章:

c# - 用一条 LINQtoSQL 语句返回不同的对象

c# - 如何使用 foreach 修改通用列表中的项目?

c# - 如何在 F# Giraffe Web API 中检索 url 编码形式?

c# - SSL通信的双向认证

perl - 将 0 作为命令行参数传递的问题

c - 双 while 循环链表导致无限循环

java - Binary Search 仅当搜索项为偶数时才创建无限循环

c - 如何检测 C 中的 CLI 特殊字符?

python - Python optparse 中的有序选项

java - 在无限循环中执行事件