Диалог выбора папки в отдельном потоке - C#

Узнай цену своей работы

Формулировка задачи:

Обьясните, пожалуйста, как починить ошибку при работе с backgroundWorker1? Программа дает пользователю возможность выбрать папку, и на форме получаю информацию об этой папке- размер, названия файлов в папке, когда файлы созданы Т.к. фаилов в папке может быть очень много,т.е обработка занимает много времени, то кинула на форму backgroundWorker1, чтобы все не зависало. Но что-то делаю не так, т.к. получаю ошибку

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.

Спасибо!
Листинг программы
  1. using System;
  2. using System.ComponentModel;
  3. using System.Data;
  4. using System.Drawing;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.IO;
  9. using System.Collections.Generic;
  10. namespace FManager
  11. {
  12. public partial class Form1 : Form
  13. {
  14. DirectoryInfo di;
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. }
  19. private void Form1_Load(object sender, EventArgs e)
  20. {
  21. }
  22. #region "The size of the directory"
  23. public long DirSize(DirectoryInfo d)
  24. {
  25. long Size = 0;
  26. // Add file sizes.
  27. FileInfo[] fis = d.GetFiles();
  28. foreach (FileInfo fi in fis)
  29. {
  30. try
  31. {
  32. Size += fi.Length;
  33. }
  34. //This exception is made for the passage of folders can not be accessed
  35. catch (UnauthorizedAccessException)
  36. {
  37. ;
  38. }
  39. }
  40. // Add subdirectory sizes.
  41. DirectoryInfo[] dis = d.GetDirectories();
  42. foreach (DirectoryInfo di in dis)
  43. {
  44. try
  45. {
  46. Size += DirSize(di);
  47. }
  48. //This exception is made for the passage of folders can not be accessed
  49. catch (UnauthorizedAccessException)
  50. {
  51. ;
  52. }
  53. }
  54. return (Size);
  55. }
  56. #endregion
  57. #region number of files in the folder
  58. public int GetNumberofFiles(string folder)
  59. {
  60. int i = 0;
  61. try
  62. {
  63. i = Directory.GetFiles(folder, "*", SearchOption.AllDirectories).Length;
  64. return i;
  65. }
  66. catch(UnauthorizedAccessException)
  67. {
  68. ;
  69. return 0;
  70. }
  71. }
  72. #endregion
  73. #region allfiles
  74. public List<string> GetAllFiles(string folder1)
  75. {
  76. List<string> filesName = new List<string>();
  77.  
  78. DirectoryInfo dir = new DirectoryInfo(folder1);
  79. foreach(FileInfo f in dir.GetFiles("*.*"))
  80. {
  81. string s = f.FullName;
  82. filesName.Add(f.FullName + " " + f.CreationTime.ToString());
  83. }
  84. return filesName;
  85. }
  86. #endregion
  87. private void button1_Click(object sender, EventArgs e)
  88. {
  89. backgroundWorker1.RunWorkerAsync();
  90. //GoStart();
  91. }
  92. public void GoStart()
  93. {
  94. if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) //Здесь Error !!! {
  95. textBox1.Text = folderBrowserDialog1.SelectedPath;
  96. di = new DirectoryInfo(textBox1.Text);
  97. textBox2.Text = DirSize(di).ToString();
  98. textBox3.Text = GetNumberofFiles(textBox1.Text).ToString();
  99. List<string> allnames = new List<string>();
  100. allnames = GetAllFiles(textBox1.Text);
  101. dgvFiles.DataSource = allnames;
  102. for (int i = 0; i < allnames.Count; i++)
  103. {
  104. listBox1.Items.Add(allnames[i]);
  105. dgvFiles.Rows[i].Cells[0].Value = allnames[i];
  106. }
  107.  
  108. }
  109. else
  110. {
  111. MessageBox.Show("Please, choose folder!");
  112. return;
  113. }
  114. }
  115. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  116. {
  117. MessageBox.Show("Start");
  118. GoStart();
  119. }
  120. private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  121. {
  122. MessageBox.Show("E N D !");
  123. }

Решение задачи: «Диалог выбора папки в отдельном потоке»

textual
Листинг программы
  1. foreach(FileInfo f in dir.GetFiles("*.*"))
  2.             {
  3.                 filesName.Add(f.FullName);
  4.                 creationTime.Add(f.CreationTime.ToString());
  5.                 lastWriteTime.Add(f.LastWriteTime.ToString());
  6.                 size.Add(f.Length.ToString());  //вот он, размер файла
  7.             }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

15   голосов , оценка 3.667 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы