I was just wondering if there is anyone out here that knows how to write a code how to check if item is an image then open with Windows image preview else open With Build in Media player.
Code is like this :
private bool listbox3job()
{
AxWMPLib.AxWindowsMediaPlayer axWmp = wfh.Child as AxWMPLib.AxWindowsMediaPlayer;
WMPLib.IWMPPlaylist playlist = axWmp.newPlaylist("myPlaylist", string.Empty);
DateTime? start = starttid2.Value;
DateTime? end = sluttid2.Value;
DateTime now = DateTime.Now;
if (start == null || end == null)
{
return false;
}
else if (now >= start.Value && now <= end.Value)
{
foreach (var selected in listBox3.Items)
{
string s = selected.ToString();
if (listBox3Dict.ContainsKey(s))
{
if (extentions.Contains(System.IO.Path.GetExtension(s).ToUpperInvariant()))
{
Process process = new Process();
process.StartInfo.FileName = "rundll32.exe";
process.StartInfo.Arguments = #"C:\WINDOWS\System32\shimgvw.dll,ImageView_Fullscreen " + listBox3Dict[s];
process.Start();
Thread.Sleep(7000);
{
exit();
}
}
else
{
WMPLib.IWMPMedia temp = axWmp.newMedia(listBox3Dict[s]);
playlist.appendItem(temp);
axWmp.settings.setMode("loop", true);
axWmp.settings.autoStart = true;
axWmp.currentPlaylist = playlist;
}
}
}
return true;
}
return false;
}
Here you are
public static List<string> extentions = new List<string> { ".JPG", ".JPE", ".BMP", ".GIF", ".PNG" };
private void Open()
{
foreach (var selected in listBox4.Items)
{
string s = selected.ToString();
if (listBox4Dict.ContainsKey(s))
{
if (extentions.Contains(Path.GetExtension(s).ToUpperInvariant()))
{
Process process = new Process();
process.StartInfo.FileName = "rundll32.exe";
process.StartInfo.Arguments = #"C:\WINDOWS\System32\shimgvw.dll,ImageView_Fullscreen " +listBox4Dict[s];
process.Start();
process.WaitForExit();
while (!process.HasExited)
Thread.Sleep(500);
}
else
{
Mediaplayer.URL = (listBox4Dict[s]);
}
}
}
}
Related
I find myself in a race condition when subscribing to the output and error stream of System.Diagnostics.Process.
Here is a minimal example of what I do:
private string execute(string command, string arguments, int mstimeout)
{
string report = string.Empty;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
Process p = new Process();
DataReceivedEventHandler ErrorDataReceived = (o, e) => { error.Append(e.Data); };
DataReceivedEventHandler OutputDataReceived = (o, e) => { output.Append(e.Data); };
try
{
p.StartInfo.FileName = command;
p.StartInfo.Arguments = arguments;
p.EnableRaisingEvents = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.OutputDataReceived += OutputDataReceived;
p.ErrorDataReceived += ErrorDataReceived;
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
p.WaitForExit(mstimeout);
report = output.ToString() + "\n" + error.ToString();
}
finally
{
p.OutputDataReceived -= OutputDataReceived;
p.ErrorDataReceived -= ErrorDataReceived;
}
return report;
}
When debugging slowly the behaviour is what I hoped it would be. When running without stops the report ends up empty.
I assume there is a race condition where the underlying streaming objects are disposed before all the output was handled.
Is there something I can do to wait for all the output to be processed?
I don't thing you can do anything. I think that Microsoft has completely miss the shot on staring process that you want to get their outputs (output and error). There will always be a problem. At the minimum, it is the race condition you have.
I reported a bug at Microsoft: https://connect.microsoft.com/VisualStudio/feedback/details/3119134/race-condition-in-process-asynchronous-output-stream-read
Just as reference, this is the code I'm using now (it contains the same race condition problem any implementation running in asynchronous mode would have).
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace HQ.Util.General
{
public class ProcessExecutionWithOutputCapture
{
// ************************************************************************
public class ProcessWithOutputCaptureResult
{
public string Error { get; internal set; }
public string Output { get; internal set; }
public string ExecutionError
{
get
{
if (String.IsNullOrEmpty(Error))
{
return Error;
}
return Exception?.ToString();
}
}
public bool HasTimeout { get; internal set; }
/// <summary>
/// Can be cancel through the eventCancel which will cancel the wait (and if set, will kill the process)
/// </summary>
public bool HasBeenCanceled { get; internal set; }
public int ExitCode { get; internal set; }
public Exception Exception { get; internal set; }
public bool HasSucceded => !HasTimeout && Exception == null;
}
// ************************************************************************
private StringBuilder _sbOutput = new StringBuilder();
private StringBuilder _sbError = new StringBuilder();
private AutoResetEvent _outputWaitHandle = null;
private AutoResetEvent _errorWaitHandle = null;
// Could be usefull when user want to exit to not wait for process to end and kill it (if wanted)
public EventWaitHandle AdditionalConditionToStopWaitingProcess { get; set; }
public bool IsAdditionalConditionToStopWaitingProcessShouldAlsoKill { get; set; }
public ProcessWindowStyle ProcessWindowStyle { get; set; } = ProcessWindowStyle.Hidden;
public bool CreateWindow { get; set; } = false;
public static ProcessWithOutputCaptureResult ExecuteWith(string executablePath, string arguments, int timeout = Timeout.Infinite, ProcessWindowStyle processWindowStyle = ProcessWindowStyle.Hidden, bool createWindow = false)
{
var p = new ProcessExecutionWithOutputCapture();
return p.Execute(executablePath, arguments, timeout);
}
// ************************************************************************
/// <summary>
/// Only support existing exectuable (no association or dos command which have no executable like 'dir').
/// But accept full path, partial path or no path where it will use regular system/user path.
/// </summary>
/// <param name="executablePath"></param>
/// <param name="arguments"></param>
/// <param name="timeout"></param>
/// <returns></returns>
private ProcessWithOutputCaptureResult Execute(string executablePath, string arguments = null, int timeout = Timeout.Infinite)
{
ProcessWithOutputCaptureResult processWithOutputCaptureResult = null;
using (Process process = new Process())
{
process.StartInfo.FileName = executablePath;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false; // required to redirect output to appropriate (output or error) process stream
process.StartInfo.WindowStyle = ProcessWindowStyle;
process.StartInfo.CreateNoWindow = CreateWindow;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
_outputWaitHandle = new AutoResetEvent(false);
_errorWaitHandle = new AutoResetEvent(false);
bool asyncReadStarted = false;
try
{
process.OutputDataReceived += ProcessOnOutputDataReceived;
process.ErrorDataReceived += ProcessOnErrorDataReceived;
process.Start();
// Here there is a race condition. See: https://connect.microsoft.com/VisualStudio/feedback/details/3119134/race-condition-in-process-asynchronous-output-stream-read
process.BeginOutputReadLine();
process.BeginErrorReadLine();
asyncReadStarted = true;
// See: ProcessStartInfo.RedirectStandardOutput Property:
// https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.Diagnostics.ProcessStartInfo.RedirectStandardOutput);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5.2);k(DevLang-csharp)&rd=true
// All 4 next lines should only be called when not using asynchronous read (process.BeginOutputReadLine() and process.BeginErrorReadLine())
//_sbOutput.AppendLine(process.StandardOutput.ReadToEnd());
//_sbError.AppendLine(process.StandardError.ReadToEnd());
//_sbOutput.AppendLine(process.StandardOutput.ReadToEnd());
//_sbError.AppendLine(process.StandardError.ReadToEnd());
var waitHandles = new WaitHandle[1 + (AdditionalConditionToStopWaitingProcess == null ? 0 : 1)];
waitHandles[0] = new ProcessWaitHandle(process);
if (AdditionalConditionToStopWaitingProcess != null)
{
waitHandles[1] = AdditionalConditionToStopWaitingProcess;
}
bool hasSucceded = false;
int waitResult = WaitHandle.WaitAny(waitHandles, timeout);
if (waitResult == 1) // The wait has been interrrupted by an external event
{
if (IsAdditionalConditionToStopWaitingProcessShouldAlsoKill)
{
process.Kill();
}
}
else if (waitResult == 0) // Process has completed normally, no timeout or external event
{
// Ensure internal process code has completed like ensure to wait until stdout et stderr had been fully completed
hasSucceded = process.WaitForExit(timeout);
if (_outputWaitHandle.WaitOne(timeout) && _errorWaitHandle.WaitOne(timeout))
{
processWithOutputCaptureResult = new ProcessWithOutputCaptureResult();
processWithOutputCaptureResult.ExitCode = process.ExitCode;
processWithOutputCaptureResult.Output = _sbOutput.ToString();
processWithOutputCaptureResult.Error = _sbError.ToString();
}
}
else // Process timeout
{
processWithOutputCaptureResult = new ProcessWithOutputCaptureResult();
processWithOutputCaptureResult.HasTimeout = true;
}
}
catch (Exception ex)
{
if (ex.HResult == -2147467259)
{
processWithOutputCaptureResult = new ProcessWithOutputCaptureResult();
processWithOutputCaptureResult.Exception = new FileNotFoundException("File not found: " + executablePath, ex);
}
else
{
processWithOutputCaptureResult = new ProcessWithOutputCaptureResult();
processWithOutputCaptureResult.Exception = ex;
}
}
finally
{
if (asyncReadStarted)
{
process.CancelOutputRead();
process.CancelErrorRead();
}
process.OutputDataReceived -= ProcessOnOutputDataReceived;
process.ErrorDataReceived -= ProcessOnOutputDataReceived;
_outputWaitHandle.Close();
_outputWaitHandle.Dispose();
_errorWaitHandle.Close();
_errorWaitHandle.Dispose();
}
}
return processWithOutputCaptureResult;
}
// ************************************************************************
private void ProcessOnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
_outputWaitHandle.Set();
}
else
{
_sbOutput.AppendLine(e.Data);
}
}
// ************************************************************************
private void ProcessOnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
_errorWaitHandle.Set();
}
else
{
_sbError.AppendLine(e.Data);
}
}
// ************************************************************************
}
}
Usage (as an application that forward the execution):
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using HQ.Util.General;
using System.Reflection;
namespace ExecutionForwarder
{
class Program
{
static void Main(string[] args)
{
Stopwatch stopwatch = Stopwatch.StartNew();
Console.WriteLine($"App: {Assembly.GetEntryAssembly().FullName}");
Console.WriteLine($"Executing from folder: {Environment.CurrentDirectory}");
Console.WriteLine($"at: {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
Console.WriteLine($"With args: [{string.Join(" ", args.Skip(1))}]");
if (args.Length == 1 && args[0].ToLower().StartsWith("-delay:"))
{
int millisec;
if (Int32.TryParse(args[0].Substring(args[0].IndexOf(":") + 1), out millisec))
{
Console.WriteLine($"Sleeping for {millisec} milliseconds and will exit.");
Thread.Sleep(millisec);
}
else
{
Console.Error.WriteLine("Error while trying to read the delay.");
Environment.ExitCode = -99;
}
}
else
{
if (args.Length == 0)
{
Console.Error.WriteLine($"Can't forward execution. There is no argument (executable) provided.");
Environment.ExitCode = -99;
}
else
{
var result = ProcessExecutionWithOutputCapture.ExecuteWith(args[0], string.Join(" ", args.Skip(1)));
Console.Write(result.Output);
Console.Error.Write(result.Error);
Environment.ExitCode = result.ExitCode;
}
}
Console.WriteLine($"Done in {stopwatch.ElapsedMilliseconds} millisecs");
}
}
}
The problem was a timeout in certain situations. I needet to Kill the Process to avoid follow up issues.
if(!p.WaitForExit(mstimeout))
{
p.Kill();
}
For good measure I threw in a cleanup in the finally part that is likely not needet.
finally
{
p.OutputDataReceived -= OutputDataReceived;
p.ErrorDataReceived -= ErrorDataReceived;
p.Dispose();
p = null;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true);
}
Edit: I deleted the finally part since the comment below seems correct.
Edit: There was a deeper problem where the timeout was hit because of a required input. I ended up invoking a different command that is silent.
For future reference - i settled on this now:
private string execute(string command, string arguments, int mstimeout)
{
bool timeout = false;
string report = string.Empty;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
Process p = new Process();
DataReceivedEventHandler StoreError = (o, e) => { error.Append(e.Data); };
DataReceivedEventHandler StoreOutput = (o, e) => { output.Append(e.Data); };
try
{
Debug.WriteLine(command);
Debug.WriteLine(arguments);
p.StartInfo.FileName = command;
p.StartInfo.Arguments = arguments;
p.EnableRaisingEvents = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.OutputDataReceived += StoreOutput;
p.ErrorDataReceived += StoreError;
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
if (!p.WaitForExit(mstimeout))
{
p.Kill();
timeout = true;
Debug.WriteLine("Process killed");
}
else
{
p.WaitForExit();
}
}
finally
{
report = output.ToString() + "\n" + error.ToString();
Debug.WriteLine(report);
p.Dispose();
}
if (timeout)
{
throw new TimeoutException("Timeout during call: " + command + " " + arguments);
}
return report;
}
This is the line in the dowork event
List<string> Result = SearchInFile(CurrentFileWithPath, textBox2.Text);
And this is the whole dowork event code
object[] CurrentStatus;
private void _FileProcessingWorker_DoWork(object sender, DoWorkEventArgs e)
{
int countmore = 0;
try
{
//object[] CurrentStatus = new object[5];
DirectoryInfo[] MySubDirectories = (DirectoryInfo[])e.Argument;
for (int i = 0; i < MySubDirectories.GetLength(0); i++)
{
DirectoryInfo MySubDirectory = MySubDirectories[i];
List<FileInfo> l = new List<FileInfo>();
CountFiles(MySubDirectory, l);
CurrentStatus = new object[6];
int totalFiles = l.Count;
CurrentStatus[3] = i.ToString();
countmore += totalFiles;
CurrentStatus[4] = countmore;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
string CurrentDirectory = "Current Directory: " + MySubDirectory.Name;
foreach (FileInfo MyFile in l)
{
CurrentStatus = new object[6];
if (_FileProcessingWorker.CancellationPending)
{
e.Cancel = true;
return;
}
if (MyFile.Extension.ToLower() == ".cs" || MyFile.Extension.ToLower() == ".vb")
{
string CurrentFile = "Current File: " + MyFile.Name;
string CurrentFileWithPath = MyFile.FullName;
CurrentStatus[0] = CurrentDirectory;
CurrentStatus[1] = CurrentFile;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
List<string> Result = SearchInFile(CurrentFileWithPath, textBox2.Text);
if (Result != null && Result.Count > 0)
{
CurrentStatus[2] = Result;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
}
}
}
}
}
catch (Exception err)
{
return;
}
}
I'm not getting errors but using a break point I see on the textBox2 text:
Text = The function evaluation requires all threads to run.
If there is no other way how to use cross thread with it ?
Hello so i created a kind of launcher application, but i have a but of a problem when i try to use the launch button it just doesn't do anything here's my code. What i need is a way to select the Arma folder trough the program that you have enterd but when i use the code it doesn't work?
private void iniSetup()
{
//Directory Read
tb_arma3dir.Text = ini.IniReadValue("Directory", "ARMA3");
tb_addondir.Text = ini.IniReadValue("Directory", "ADDON");
}
private void arma2OACheck()
{
string arma3Path = tb_arma3dir.Text;
if (arma3Path.EndsWith(#"\"))
arma3Path = arma3Path.TrimEnd('\'');
if(!File.Exists(arma3Path + "\\ArmA2OA.exe"))
{
a3dir_pic.Source = new BitmapImage(new Uri("./Resources/redX.png", UriKind.Relative));
a2Good = false;
}
else
{
a3dir_pic.Source = new BitmapImage(new Uri("./Resources/greenCheck.png", UriKind.Relative));
a2Good = true;
}
}
private void addonDirCheck()
{
string addonPath = tb_addondir.Text;
if (addonPath.EndsWith(#"\"))
addonPath = addonPath.TrimEnd('\'');
if (!Directory.Exists(addonPath))
{
addondir_pic.Source = new BitmapImage(new Uri("./Resources/redX.png", UriKind.Relative));
addonGood = false;
}
else
{
addondir_pic.Source = new BitmapImage(new Uri("./Resources/greenCheck.png", UriKind.Relative));
addonGood = true;
}
}
private void CompileLaunchParams()
{
string launchStr = "";
// Lauch parameters
launchStr += #"-mod=#TCG" + #" -ip=31.186.251.207" + #" -port=2302" + " -nosplash" + "-world=empty" + "-nosplash";
// Parse game path
string filename = "iniSetup";
// Start game process as administrator
ProcessStartInfo info = new ProcessStartInfo(filename); // what do i use to select the program so it can execute?
info.UseShellExecute = true;
info.Verb = "runas";
info.Arguments = launchStr;
Process.Start(info);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if(a2Good & addonGood ) // if the addon and arma is good it launches
{
CompileLaunchParams();
}
else
{
MessageBox.Show("Not all settings are configured, Please click the gear in the top right to define options!");
}
}
You can try save selected path to field in class like:
private string Arma3Path;
private void arma2OACheck()
{
string path = tb_arma3dir.Text;
if (path.EndsWith(#"\"))
Arma3Path = path.TrimEnd('\'') + "\\ArmA2OA.exe";
if(!File.Exists(Arma3Path))
{
a3dir_pic.Source = new BitmapImage(new Uri("./Resources/redX.png", UriKind.Relative));
a2Good = false;
}
else
{
a3dir_pic.Source = new BitmapImage(new Uri("./Resources/greenCheck.png", UriKind.Relative));
a2Good = true;
}
}
and then use it like
private void CompileLaunchParams()
{
string launchStr = "";
// Lauch parameters
launchStr += #"-mod=#TCG" + #" -ip=31.186.251.207" + #" -port=2302" + " -nosplash" + "-world=empty" + "-nosplash";
// Parse game path
string filename = Arma3Path;
// Start game process as administrator
ProcessStartInfo info = new ProcessStartInfo(filename); // what do i use to select the program so it can execute?
info.UseShellExecute = true;
info.Verb = "runas";
info.Arguments = launchStr;
Process.Start(info);
}
public bool DownloadMp3File (DownloadedMp3 mp3) {
WebClient client = new WebClient ();
string filePath = "";
bool wasDownload = false;
try {
string song = mp3.SongName;
filePath = #"mp3\" + song + ".mp3";
if (File.Exists (filePath)) {
File.Delete (filePath);
}
DateTime tryCountNow = DateTime.Now;
client = new WebClient ();
client.DownloadFileAsync (new Uri (mp3.Url), filePath);
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
DateTime start = DateTime.Now;
bool notDownload = false;
downloadComplete = false;
while (!downloadComplete) {
DateTime now = DateTime.Now;
TimeSpan ts = now - start;
int min = ts.Minutes;
int sec = ts.Seconds;
if (10 < sec && 0 == downloadProgress) {
notDownload = true;
client.CancelAsync ();
break;
}
if (min == 1) {
notDownload = true;
client.CancelAsync ();
break;
}
Thread.Sleep (30);
}
if (!notDownload) {
client.CancelAsync ();
client.OpenRead (mp3.Url);
int downloadedFileSize = Convert.ToInt32 (client.ResponseHeaders["Content-Length"]);
FileInfo localFile = new FileInfo (filePath);
if (localFile.Length == downloadedFileSize) {
wasDownload = true;
}
}
}
catch {
downloadProgress = 0;
downloadComplete = false;
}
finally {
client.CancelAsync ();
client.Dispose ();
downloadComplete = false;
downloadProgress = 0;
GC.Collect ();
if (!wasDownload) {
if (File.Exists (filePath)) {
FileSecurity fs = File.GetAccessControl (filePath);
File.Delete (filePath);
}
}
Application.Current.Dispatcher.BeginInvoke (
DispatcherPriority.Background,
new Action (() =>
MainWindow.label3.Content = ""
));
}
return wasDownload;
}
Please help! I sometimes get that exception:
File.Delete the process cannot access the file because it is being used by another process
I can't find out why (I disposed WebClient).
Your code suggests you're getting the "file being used" exception on a file that was newly downloaded. Many anti-virus programs automatically scan newly created and/or newly downloaded files, and may delay closing the file handle until the scan is done.
If that is your problem, then there's nothing more you can to do close the file on time. You can either switch to a different anti-virus that doesn't keep files locked during scans, or you can implement a delay+retry loop when trying to use a file that's recently been closed.
I am use SafeFileEnumerator class to search for files inside folder root, this class return only files from location with permission so I am use it successfully.
When I try to fill my list in this way all works fine:
List<string> list = new List<string>();
list = SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath,
"*.*", SearchOption.AllDirectories).ToList();
But in this case my GUI freeze so I move it to new thread and in this case nothing happen and I wondered why:
private void btnAddDir_Click(object sender, EventArgs e)
{
List<string> list = new List<string>();
string fileToAdd = string.Empty;
List<string> filesList = new List<string>();
dialog = folderBrowserDialog1.ShowDialog();
tbAddDir.Text = folderBrowserDialog1.SelectedPath;
string pathToSearch = folderBrowserDialog1.SelectedPath;
if (dialog == DialogResult.OK)
{
toolStripStatusLabel.Text = "Search for pcap files...";
groupBoxRootDirectory.Enabled = false;
btnStart.Enabled = false;
ThreadStart starter = delegate
{
list = SafeFileEnumerator.EnumerateFiles(pathToSearch, "*.pcap", SearchOption.AllDirectories).ToList();
};
Thread t = new Thread(starter);
t.IsBackground = true;
t.Start();
if(list.Count != 0)
AddFilesToListBox(list);
}
}
SafeFileEnumerator class code:
public static class SafeFileEnumerator
{
public static IEnumerable<string> EnumerateDirectories(string parentDirectory, string searchPattern, SearchOption searchOpt)
{
try
{
var directories = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
directories = Directory.EnumerateDirectories(parentDirectory).SelectMany(x => EnumerateDirectories(x, searchPattern, searchOpt));
}
return directories.Concat(Directory.EnumerateDirectories(parentDirectory, searchPattern));
}
catch (UnauthorizedAccessException ex)
{
return Enumerable.Empty<string>();
}
}
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOpt)
{
try
{
var dirFiles = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
dirFiles = Directory.EnumerateDirectories(path).SelectMany(x => EnumerateFiles(x, searchPattern, searchOpt));
}
return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
}
catch (UnauthorizedAccessException ex)
{
return Enumerable.Empty<string>();
}
}
}
after my list is full of files:
private void AddFilesToListBox(List<string> filesList)
{
string fileToAdd = string.Empty;
Editcap editcap = new Editcap();
Capinfos capinfos = new Capinfos();
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork +=
(s1, e1) =>
{
foreach (string fileName in filesList)
{
FileInfo fileInfo = new FileInfo(fileName);
if (checkFileCreationDate(fileInfo))
{
if (editcap.isWiresharkFormat(fileInfo.FullName))
{
if (editcap.isLibpcapFormat(fileInfo.FullName))
{
addFileToListBox(fileInfo.FullName, capinfos.getFileDuration(fileInfo.FullName));
}
else if (!editcap.isLibpcapFormat(fileInfo.FullName))
{
fileToAdd = editcap.getNewFileName(fileInfo.FullName);
if (new FileInfo(fileToAdd).Exists && !fileInfo.Exists)
{
addFileToListBox(fileToAdd, capinfos.getFileDuration(fileInfo.FullName));
}
}
}
}
//this.Invoke((MethodInvoker)delegate { lvFiles.Items[lvFiles.Items.Count - 1].Selected = true; });
toolStripStatusLabel.Text = string.Format("{0} files were added", lvFiles.Items.Count);
}
//this.Invoke((MethodInvoker)delegate { lvFiles.Items[lvFiles.Items.Count - 1].Selected = true; });
};
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s1, e1) =>
{
groupBoxRootDirectory.Enabled = true;
btnClear.Enabled = true;
if (lvFiles.Items.Count != 0)
btnStart.Enabled = true;
toolStripStatusLabel.Text = string.Format("{0} files were added", lvFiles.Items.Count);
if (tbAddDir.Text != "")
{
listener = new FileListener();
listener.startListener(tbAddDir.Text);
listener._newFileEventHandler += listener_newFileEventHandler;
}
});
backgroundWorker.RunWorkerAsync();
}
after t.start() i am call AddFilesToListBox(list);
You did not implemented an asynchronous pattern.
After t.Start(); is called, the thread did not finished its work yet, so your list was still empty at the time you called AddFilesToListBox. Do implement an async pattern and call AddFilesToListBox once the thread finished its job.