使用StreamWriter编写文件需要花费很长时间&自动重新加载窗口

本文关键字:新加载 窗口 加载 长时间 文件 StreamWriter 使用 | 更新日期: 2023-09-27 17:50:36

在我的程序中,我使用Window_Loaded事件将我的App.config文件写入.exe的目录,因为我需要它用于那里的connectionString。

它工作得很好,但是在使用StreamWriter时似乎很慢,并且它似乎一写完就重新加载窗口。

我的意思是:窗口完全加载(控件被渲染等),我的代码末尾显示了MessageBox,但文件仍然不在那里。之后,窗口消失,重新出现,再次显示消息框&只有这样。config文件才会被完全写入和加密。

此外,即使在文件被写入之前,由于某种原因,我的Loaded事件中的其余代码似乎保持工作,而不是加载事件暂停,直到StreamWriter完成。

我没主意了,有什么方法可以提高文件写入的速度,以及我如何才能适当地停止程序的执行,直到写入完成?

我的当前代码:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    string loc = Assembly.GetExecutingAssembly().Location;
    if (File.Exists(loc + ".config"))
        File.Delete(loc + ".config");
    string result = "";
    using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Hub.Resources.Hub.exe.config"))
    using (StreamReader reader = new StreamReader(stream))
    {
        result = reader.ReadToEnd();
    }
    //I've also tried using File.WriteAllText(...), same result
    using (StreamWriter wr = new StreamWriter(loc + ".config"))
    {
        wr.Write(result);
    }
    //Encrypt config file
     Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    ConfigurationSection s = conf.GetSection("connectionStrings");
    if (s != null)
    {
        s.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
        s.SectionInformation.ForceSave = true;
        conf.Save(ConfigurationSaveMode.Full);
    }
    //Show messagebox to notify me (purely informational, will be deleted after it's finished)
    //This messagebox seems to be shown twice, once before the file is written, once after it's written & encrypted.
    MessageBox.Show("Finished Loading");
}

PS:在调试期间,这一切都完全正常,没有窗口被重新加载,文件立即出现,因为它应该。

使用StreamWriter编写文件需要花费很长时间&自动重新加载窗口

原来是我的防病毒软件迫使。exe首先在沙盒模式下运行。

不是代码错误,一旦我将我的。exe添加到AV的排除项中,它就能100%正确地工作,就像在调试一样。

显然腾讯认为我的程序是一个木马,虽然没有线索的原因,但我必须说这是一种有趣的:-)

VirusTotal

所以如果有人遇到窗口加载两次或不能正常工作的问题。尝试将.exe添加到AV排除列表中;-)