Writing to outputfile within thread execution - c#

I have following code, but if I use Console.ReadKey() then the output is written to file once I close the console, but I have to press key to exit the app. If I comment the Console.Readkey() the code exit, but output file is blank, how can I write to output file and exit the application without any manual key press ?
static void Main(string[] args)
{
try
{
int i = 1;
string[] lines = System.IO.File.ReadAllLines(#"C:\Software\ThreadTest1\ServerList.txt");
/*
ServerList.txt has file windows server names in it
*/
foreach (string linevalue in lines)
{
var value = i;
var runningTask = Task.Factory.StartNew(() => fillServiceAccountDetailsinGrid(linevalue.ToString(), value));
i = i + 1;
}
// Console.ReadKey(); // if I uncomment this list, only then the output file has message written, but then console
}
catch (Exception ex)
{
string path = #"C:\Software\ThreadTest1\Output_ServerList_Log2.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Error occurred on : " + DateTime.Now.ToString() + " : Error occurred in module 'writetoDatabase' Description : " + ex.Message.ToString());
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("Error occurred on : " + DateTime.Now.ToString() + " : Error occurred in module 'writetoDatabase' Description : " + ex.Message.ToString());
}
}
}
}
private static void fillServiceAccountDetailsinGrid(string srvName, int i)
{
try
{
string path = #"C:\Software\ThreadTest1\" + srvName.ToString() + ".txt";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Error occurred on : " + DateTime.Now.ToString() + " : Error occurred in module 'writetoDatabase' Description : " + srvName.ToString());
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("Error occurred on : " + DateTime.Now.ToString() + " : Error occurred in module 'writetoDatabase' Description : " + srvName.ToString());
}
}
Thread.Sleep(50);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}

You are firing off Tasks asynchronously and not waiting for them to complete.
If you want synchronous concurrency try replacing your foreach loop with the following...
Parallel.For(0, lines.Length, (int lineId) =>
{
fillServiceAccountDetailsinGrid(lines[lineId].ToString(), lineId);
});
...this will not return until all actions have completed.

#Creyke is correct this is issue with task management .
List<Task> tasklist = new List<Task>();
foreach (string linevalue in lines)
{
var value = i;
tasklist.Add(Task.Factory.StartNew(() => fillServiceAccountDetailsinGrid(linevalue.ToString(), value)));
i = i + 1;
}
Task.WaitAll(tasklist.ToArray());
wating for all task will fix this.

Related

File.Move issue: Process cannot access the file exception

I am getting an error when I run this newFile method:
class logFile
{
public static string logpath = #"D:\Program Files\CustomApps\DataFeed\";
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss");
Console.WriteLine(timestamp + log);
File.AppendAllText(logpath + #"log_file_current.txt", timestamp + log + Environment.NewLine);
}
public static void newFile()
{
if (File.Exists(logpath + #"log_file_current.txt") == true)
{
File.Move(logpath + #"log_file_current.txt"
, logpath + #"log_files\log_file_ORPHANED_" + DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ".txt");
}
try
{
File.Create(logpath + #"log_file_current.txt");
logFile.log("logFile created.");
}
catch(System.NotSupportedException ex)
{
Console.WriteLine(ex.Message);
}
}
}
I get the following error:
If I comment the body of the "newFile" code out then it runs without error, but then I would need to manually archive. If I comment out the File.Move part it all runs fine so this is the culprit.
How can I release the file so that it can be moved?
You need to use File.Close after using File.Create, this is why you are getting an error saying the file is used by another process. Try adding this line to your code :
try
{
File.Create(logpath + #"log_file_current.txt").Close(); // Notice the .Close() here
logFile.log("logFile created.");
}
Source : Closing a file after File.Create
Try this one
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ": ";
Console.WriteLine(timestamp + log);
using (StreamWriter sw = File.AppendText(logpath + #"log_file_current.txt"))
{
sw.WriteLine(timestamp + log);
}
}

Copying a file that is a virus caused my program to terminate

I have made a tool that will copy files from a source to a destination. However during the copy, the software came across a virus that was flagged by the anti-virus software (Symantec).
The anti-virus then caused my software to close down, and quarantine the program as a "dropper".
Is there anyway I can gracefully handle this scenario, rather than shutting down my program completely?
I appreciate that the action was the result of the anti-virus, but is there anything I can do to help the situation? For example, Robocopy does not just terminate when it comes across a virus.
Here is my copy code;
void CopyFileExactly(CopyParameterBundle cpb, bool overwrite)
{
string CTP = "", CFP = "";
CFP = cpb.SourcePath;
if (cpb.RenameFile)
CTP = cpb.DestPath ;
else
CTP = cpb.DestPath;
//Check firstly if the file to copy exists
if (!File.Exists(CFP))
{
throw new FileNotFoundException();
}
//Check if destination file exists
//If it does, make it not read only so we can update MAC times
if (File.Exists(CTP))
{
var target = GetFile(CTP);//new FileInfo(CTP);
if (target.IsReadOnly)
target.IsReadOnly = false;
}
var origin = GetFile(CFP);//new FileInfo(CFP);
GetFile(CTP).Directory.Create();
//(new FileInfo(CTP)).Directory.Create();
origin.CopyTo(CTP, (overwrite ? true : false));
if (!File.Exists(CTP))
{
throw new FileNotFoundException("Destination file not found!");
}
var destination = GetFile(CTP);//new FileInfo(CTP);
if (destination.IsReadOnly)
{
destination.IsReadOnly = false;
destination.CreationTime = origin.CreationTime;
destination.LastWriteTime = origin.LastWriteTime;
destination.LastAccessTime = origin.LastAccessTime;
destination.IsReadOnly = true;
}
else
{
destination.CreationTime = origin.CreationTime;
destination.LastWriteTime = origin.LastWriteTime;
destination.LastAccessTime = origin.LastAccessTime;
}
if (performMD5Check)
{
var md5Check = compareFileMD5(CFP, CTP);
cpb.srcMD5Hash = md5Check.Item2;
cpb.dstMD5Hash = md5Check.Item3;
if (!md5Check.Item1)
throw new MD5MismatchException("MD5 Hashes do NOT match!");
}
}
The calling code;
void BeginCopy(int DegreeOfParallelism, int retryCount, int retryDelay)
{
object _lock;
//Setup cancellation token
po.CancellationToken = cts.Token;
//Set max number of threads
po.MaxDegreeOfParallelism = DegreeOfParallelism;
//Exceptio logging queue
var exceptions = new ConcurrentQueue<Exception>();
var completeItems = new ConcurrentQueue<CopyParameterBundle>();
var erroredItems = new ConcurrentQueue<CopyParameterBundle>();
//Logger logger = new Logger(sLogPath);
//logger.Write("Starting copy");
Task.Factory.StartNew(() =>
{
Parallel.ForEach(CopyParameters,
po,
(i, loopState, localSum) =>
{
localSum = retryCount;
do
{
try
{
//Go off and attempt to copy the file
DoWork(i);
//Incrememt total count by 1 if successfull
i.copyResults.TransferTime = DateTime.Now;
i.copyResults.TransferComplete = true;
completeItems.Enqueue(i);
//logger.Write("Copied file from: " + i.SourcePath + "\\" + i.SourceFile + " => " + i.DestPath + "\\" + i.SourceFile);
break;
}
catch (Exception ex)
{
//this.richTextBox1.AppendText("[-] Exception on: " + i.SourcePath + "\\" + i.SourceFile + " => " + ex.Message.ToString() + System.Environment.NewLine);
//Exception was thrown when attempting to copy file
if (localSum == 0)
{
//Given up attempting to copy. Log exception in exception queue
exceptions.Enqueue(ex);
this.SetErrorText(exceptions.Count());
//Write the error to the screen
this.Invoke((MethodInvoker)delegate
{
this.richTextBox1.AppendText("[-] Exception on: " + i.SourcePath + "\\" + i.SourceFile + " => " + ex.Message.ToString() + System.Environment.NewLine);
i.copyResults.TransferComplete = false;
i.copyResults.TransferTime = DateTime.Now;
i.copyResults.exceptionMsg = ex;
erroredItems.Enqueue(i);
//logger.Write("ERROR COPYING FILE FROM : " + i.SourcePath + "\\" + i.SourceFile + " => " + i.DestPath + "\\" + i.SourceFile + " => " + ex.Message.ToString() + " => " + ex.Source);
});
}
//Sleep for specified time before trying again
Thread.Sleep(retryDelay);
localSum--;
}
//Attempt to Repeat X times
} while (localSum >= 0);
//Check cancellation token
po.CancellationToken.ThrowIfCancellationRequested();
Interlocked.Increment(ref TotalProcessed);
this.SetProcessedText(TotalProcessed);
//Update Progress Bar
this.Invoke((MethodInvoker)delegate
{
this.progressBar1.Value = (TotalProcessed);
});
});
//aTimer.Stop();
this.Invoke((MethodInvoker)delegate
{
this.label9.Text = "Process: Writing Log";
});
WriteLog(sLogPath, completeItems, erroredItems);
this.Invoke((MethodInvoker)delegate
{
this.label9.Text = "Process: Done!";
});
if (exceptions.Count == 0)
MessageBox.Show("Done!");
else
MessageBox.Show("Done with errors!");
EnableDisableButton(this.button2, true);
EnableDisableButton(this.button4, false);
});
}
What happened is most likely that the antivirus was aware of the virus file, so when it detected that a change in the file system (moving the file) occurred, it terminated the program because by moving the virus to a different location in your computer, it could cause problems (since it's a virus). It was flagged as dropper, basically a type of program that is designed to install the virus.
Edit: i forgot to mention that to solve the problem you will most likely need to license your program.

Deleting files inside folder in C#

I am creating application to delete files for more than 15 days in past, I've created a project using the C# language "multithreading" to be able to delete these files, but its only reading the first file with the error
The directory name is invalid
Can anyone help me on this please?
private void process3()
{
//DirectoryInfo info1 = new DirectoryInfo(#"\\10.4.9.202\d\PapyrusRes\appdata\");
DirectoryInfo info1 = new DirectoryInfo(#"\\DXB-RASO-MCH\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2");
// long Size = 0;
//C:\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2
String[] filePaths = (from fls in info1.EnumerateFiles()
where (fls.LastWriteTime.Date < DateTime.Today.AddDays(-15))
select fls.FullName).ToArray();
int i = 0;
if (!File.Exists(logPath3))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logPath3))
{
sw.WriteLine("Deletion Process History:");
sw.WriteLine(" ");
sw.WriteLine(" ");
}
}
//stopwatch.Start();
try
{
foreach (String f in filePaths)
{
DirectoryInfo info = new DirectoryInfo(f);
int difference = DateTime.Today.Subtract(info.LastWriteTime).Days;
textBox2.BeginInvoke(new Action(() =>
{
textBox2.Text += "Folder Name: " + Path.GetFileName(f) +
"\r\nDate Modified: " + difference +
"\r\n------\r\n";
}));
Thread.Sleep(10);
i++;
Directory.Delete(f, true);
count++;
}
using (StreamWriter sw = File.AppendText(logPath3))
{
sw.WriteLine("Successful at: " + DateTime.Now + " " + count +
" files were deleted");
}
}
catch (Exception ex)
{
// log errors
// Write your content here
using (StreamWriter sw = File.AppendText(logPath3))
{
if (count == 0)
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " Error: " +
ex.Message);
else
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " " + count +
" files were deleted" + " Error: " + ex.Message);
}
}
}

Unable to catch the exception from selenium in C#

I have written some code which deals with C# reflections and selenium to automate the build process of a URL.
But I am unable to catch the exception. What I did is , I exported into .html format from selenium IDE. and parsed and it automatically calls the function related to it from c# code.
but I am unable to catch it. I need help in this regard? Any guesses why it is unable to catch the exception..
I am using Visual Studio Microsoft Visual C# 2010 Express.
And the code is as follows.
using System;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Selenium;
using System.Reflection;
using System.IO;
namespace SeleniumTests
{
public class Program
{
public ISelenium selenium;
public void SetupTest()
{
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "URL");
selenium.Start();
}
//[TearDown]
public void TeardownTest()
{
try
{
selenium.Stop();
}
catch (Exception)
{
}
}
public void myFun(string file)
{
bool flag = false;
string targetString = "", valueString = "", commandString = "";
string subString1, subString2;
HtmlAgilityPack.HtmlNode commandNode=null;
HtmlAgilityPack.HtmlNode targetNode=null;
HtmlAgilityPack.HtmlNode valueNode=null;
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(file);
doc.OptionCheckSyntax = true;
doc.OptionFixNestedTags = true;
doc.OptionAutoCloseOnEnd = true;
doc.OptionOutputAsXml = true;
doc.OptionDefaultStreamEncoding = Encoding.Default;
HtmlAgilityPack.HtmlNode table = doc.DocumentNode.SelectSingleNode("//table");
foreach (var row in table.SelectNodes("//tr"))
{
commandNode = row.SelectSingleNode("td[1]");
commandString = commandNode.InnerHtml.ToString();
subString1 = commandString.Substring(0, 1);
subString1 = subString1.ToUpper();
subString2 = commandString.Substring(1, commandString.Length - 1);
commandString = subString1 + subString2;
targetNode = row.SelectSingleNode("td[2]");
if (targetNode != null)
{
targetString = targetNode.InnerHtml.ToString();
if (targetString.Length == 0)
{
targetNode = null;
}
}
valueNode = row.SelectSingleNode("td[3]");
if (valueNode != null)
{
valueString = valueNode.InnerHtml.ToString();
if (valueString.Length == 0)
{
valueNode = null;
}
}
MethodInfo SeleniumMethod = typeof(ISelenium).GetMethod(commandString);
if (SeleniumMethod == null)
{
// Console.WriteLine(" \n NULL " + commandString);
continue;
}
if (targetNode == null && valueNode == null)
continue;
if (targetNode != null && valueNode != null)
{
String[] SeleniumArgs = new String[2];
SeleniumArgs[0] = targetNode.InnerHtml.ToString();
SeleniumArgs[1] = valueNode.InnerHtml.ToString();
try
{
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
catch (System.Reflection.TargetInvocationException)
{
}
catch (Selenium.SeleniumException se)
{
flag = true;
string lines = "\n Selenium Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
}
catch (Exception e)
{
flag = true;
string lines = "\n Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
}
}
else if (targetNode != null && valueNode == null)
{
String[] SeleniumArgs = new String[1];
SeleniumArgs[0] = targetNode.InnerHtml.ToString();
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
else if (valueNode != null)
{
String[] SeleniumArgs = new String[1];
SeleniumArgs[0] = valueNode.InnerHtml.ToString();
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
}// end of for
string line = "\n Script executed successfully ";
if (flag == false)
{
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(line);
writer.Flush();
writer.Close();
}
}
}
}
public class TestProgram
{
static void Main(string[] args)
{
try
{
Program p = new Program();
p.SetupTest();
string file = #"1.html";
p.myFun(file);
p.TeardownTest();
}
catch { }
}
}
}
If you are trying to catch the exception in your Main() method, you need to bubble your exceptions up in your myFun method. At the moment you are drowning any exceptions in your myFun method.
e.g.
try
{
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
catch (System.Reflection.TargetInvocationException)
{
throw; //make this bubble up to the calling method.
}
catch (Selenium.SeleniumException se)
{
flag = true;
string lines = "\n Selenium Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
throw se; //bubble up to calling method
}
//etc...

How can I write a console application which can search Users Directory?

I asked guru but I still couldn't solve the problem that I have.
I want to write a console program searching certain files, like xls, doc or *pdf.
I wrote a code like this but when it comes to the say, Users Directory, it cates UnauthorizedAccessException.
How can I write a console application which can search Users Directory?
I set clickonce off and build it with manifest which requireAdministrator.
So, on Vista or 7, it runs as an administrator, with the elevation dialogue.
Here's the full code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
//
private const string FILE_NAME = "search.txt";
private const string SEARCH_WORDS1 = "*.doc";
private const string SEARCH_WORDS2 = "*.ppt";
private const string SEARCH_WORDS3 = "*.jtd";
private const string SEARCH_WORDS4 = "*.pdf";
private const string END_WORDS = "\r\nSearch is finished.\r\n";
//This funcion echoes the messages.
void FileCheck()
{
string echo_words = "\r\nNow starts searching these files!" + SEARCH_WORDS1 + " "
+ SEARCH_WORDS2 + " " + SEARCH_WORDS3 + " " + SEARCH_WORDS4 + " "
+ "!\r\n";
if (File.Exists(FILE_NAME))
{
Console.WriteLine("{0} is already exists. Replace it to the new one.", FILE_NAME);
Console.WriteLine(echo_words);
File.Delete(FILE_NAME);
using (StreamWriter sw = File.CreateText(FILE_NAME))
{
sw.WriteLine(FILE_NAME + " is already exists. Replace it to the new one.\r\n");
sw.WriteLine(echo_words);
sw.Close();
}
}
else
{
using (StreamWriter sw = File.CreateText(FILE_NAME))
{
Console.WriteLine(echo_words);
sw.WriteLine(echo_words);
sw.Close();
}
}
}
//This function write to a file that search is finished.
void EndMessage()
{
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
Console.WriteLine(END_WORDS);
sw.WriteLine(END_WORDS);
sw.Close();
}
}
//This function searches files given and write to a file.
void DirSearch(string sDir, string SEARCH_WORDS, int row)
{
int i;
i = 0;
string DeviceError = "off";
try
{
foreach (var d in Directory.GetDirectories(sDir))
{
DirectoryInfo di = new DirectoryInfo(d);
if ((di.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) {
//ReparsePoint could not be serached
continue;
}
try
{
foreach (string file in Directory.GetFiles(d, SEARCH_WORDS, SearchOption.AllDirectories))
{
Console.WriteLine(file);
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(file);
sw.Close();
i++;
}
}
}
catch (UnauthorizedAccessException)
{
//Unauthorized
Console.WriteLine(d + " is not allowd to be read !!");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(d + " is not allowd to be read");
sw.Close();
}
}
}
}
catch (IOException)
{
//Device is not ready
DeviceError = "on";
}
if (DeviceError == "off")
{
if (i > 0)
{
Console.WriteLine(i + "numbers " + SEARCH_WORDS + " Files were found!\r\n");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(i + "numbers " + SEARCH_WORDS + " Files were found!\r\n");
sw.Close();
}
}
else
{
Console.WriteLine(SEARCH_WORDS + " Files were not found !\r\n");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine(SEARCH_WORDS + " Files were not found !\r\n");
sw.Close();
}
}
}
}
//Main
static void Main(string[] args)
{
Program x = new Program();
string[] drives = Environment.GetLogicalDrives();
int row = drives.GetLength(0);
string my_documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Console.WriteLine("Logical Drives are " + row + ".");
using (StreamWriter sw = File.AppendText(FILE_NAME))
{
sw.WriteLine("Logical Drives are " + row + ".");
sw.Close();
}
int i = 0;
x.FileCheck();
while (row > 0)
{
x.DirSearch(drives[i], SEARCH_WORDS1, row);
x.DirSearch(drives[i], SEARCH_WORDS2, row);
x.DirSearch(drives[i], SEARCH_WORDS3, row);
x.DirSearch(drives[i], SEARCH_WORDS4, row);
row--;
i++;
}
x.EndMessage();
}
}
}
The error you're getting is caused by the file system permissions. The only way around would be to grant the credentials you're using access to the specified folders, run the application as 'Administrator' or run the application as the specific user for each User's folder.

Categories