Please suggest whats wrong with the following code to write names to text file. The file is being created but nothing is written in it. Although program is running fine and there is no exception yet not getting anything in txt file.
class IO
{
public void write(string name)
{
try
{
FileStream fs = new FileStream(#"D:\Infogain\ObjSerial.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.Current);
sw.Write(name);
fs.Close();
}
catch (Exception ex)
{
Console.WriteLine("Issue in writing: " + ex.Message);
}
}
public static void Main(string[] args)
{
string name;
int ch;
List<string> list = new List<string>();
do
{
Console.WriteLine("Enter name");
name = Console.ReadLine();
IO io = new IO();
io.write(name);
Console.WriteLine("Enter 1 to continue");
ch = Convert.ToInt32(Console.ReadLine());
}while(ch==1);
}
}
You should read up on Object Oriented Programming a little. Creating a new IO object within that loop makes no sense. Also your write function is kind of messed up.
Fixed version:
(note: "write" function appends to file)
public class IO
{
public static void write(string name)
{
try
{
string path = #"e:\mytxtfile.txt";
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(name);
}
}
catch (Exception ex)
{
Console.WriteLine("Issue in writing: " + ex.Message);
}
}
public static void Main(string[] args)
{
string name;
int ch;
List<string> list = new List<string>();
do
{
Console.WriteLine("Enter name");
name = Console.ReadLine();
write(name);
Console.WriteLine("Enter 1 to continue");
ch = Convert.ToInt32(Console.ReadLine());
} while (ch == 1);
}
}
Related
I'm having an issue at the moment which I am trying to fix.
Trying to concatenate the values(Free space left in my SSD+ time of execution)after each scan I do (the scans are scheduled)and will be saved in a csv file.
using System;
using System.IO;
namespace SSD
{
public class Program
{
static void Main(string[] args)
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady == true)
{
var t = d.AvailableFreeSpace;
var AvailableFree = (t / Math.Pow(10, 9)) - 10;
var timeOnly = DateTime.Now;
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
try
{
ostrm = new FileStream(#"path.csv", FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter(ostrm);
writer.Write(AvailableFree +","+ timeOnly);
}
catch (Exception e)
{
Console.WriteLine("Cannot open file.csv for writing");
Console.WriteLine(e.Message);
return;
}
Console.SetOut(writer);
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
Console.WriteLine("Done");
while (true) { }
}
}
}
}
}
}
May anyone tell me what I am doing wrong?
Kind regards
I am creating console app to simulate server. I create multiple virus files together using multiple threads to see whether all files get quarantined, if yes, how long it takes to quarantined. The problem with multithreading application is one thread starts writing another thread so I get exception - The process can not access the file X because the file is being used by another process. This is the reason that all files don't get quarantined. I use framework 4.5.2
I have created app using thread and task. I don't get the desire result. What is the best practice to write this app? Thank you for helping me in advance.
Using Thread:
class Program
{
static string folderPath;
static readonly string fileContent = #"X5O!P%#AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";
static void Main(string[] args)
{
folderPath = "F:\VirusScan";
int counter = 1000;
for (int i = 0; i < counter; i++)
{
var thread = new Thread(() => GenerateVirusFile(i));
thread.Start();
}
Console.ReadKey();
}
static void GenerateVirusFile(int i)
{
string filePath = $#"{folderPath}\TestForVirusScan_{i}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.txt";
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(fileContent);
}
var timer = Stopwatch.StartNew();
while (true)
{
if (!File.Exists(filePath))
{
Console.WriteLine($"{i}: File was removed in {timer.ElapsedMilliseconds}ms");
break;
}
else
{
Thread.Sleep(1);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"{i}: Exception {ex.GetType().Name} occurred: {ex.Message}");
}
}
}
Using Task:
class Program
{
static string folderPath;
static readonly string fileContent = #"X5O!P%#AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";
static void Main(string[] args)
{
folderPath = "F:\VirusScan";
int counter = 1000;
List<Task> tasks = new List<Task>();
for (int i = 1; i <= counter; i++)
{
Task newTask = new Task((x) => GenerateVirusFile(x), i);
tasks.Add(newTask);
}
foreach (var task in tasks)
{
task.Start();
}
Task.WaitAll(tasks.ToArray());
Console.ReadKey();
}
public static void GenerateVirusFile(object i)
{
string filePath = $#"{folderPath}\TestForVirusScan_{i}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.txt";
try
{
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(fileContent);
}
var timer = Stopwatch.StartNew();
while (true)
{
if (!File.Exists(filePath))
{
Console.WriteLine($"{i}: File was removed in {timer.ElapsedMilliseconds}ms");
break;
}
else
{
Thread.Sleep(1);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"{i}: Exception {ex.GetType().Name} occurred: {ex.Message}");
}
}
}
The problem is in the following code:
for (int i = 0; i < counter; i++)
{
var thread = new Thread(() => GenerateVirusFile(i));
thread.Start();
}
The closure () => GenerateVirusFile(i) is referencing changing variable
Rewrite it in the following way:
Parallel.For(0, counter, GenerateVirusFile);
Have you tried something like this in your loop:
int x = i;
var thread = new Thread(() => GenerateVirusFile(x));
this prevents that the same i is used for more threads/file names.
I've created a fileStream and a streamwriter to write to this. Problem is my file is not showing up with any text. The objects have instantiated correctly and the path and everything is write, just can't see anything writing. Maybe a problem with the streamwriter?
public class Logger {
StreamWriter sw;
FileStream logFileStream;
public enum LogLevel
{
Low,
Medium,
High
};
public Logger(string filePath)
{
//logStream = new StreamWriter(logFilePath, false);
logFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Write);
sw = new StreamWriter(logFileStream);
}
public void LogMessage(string message) {
LogMessage(message, LogLevel.Low, false);
}
public void LogMessage(string message, LogLevel level, bool excludeFromLogFile){
var prefix = string.Empty;
ConsoleColor color = ConsoleColor.White;
switch (level)
{
case LogLevel.Medium:
prefix = "?";
color = ConsoleColor.Yellow;
break;
case LogLevel.High:
prefix = "!";
color = ConsoleColor.Red;
break;
}
if (!excludeFromLogFile)
{
sw.WriteLine("{0} {1} {2}", prefix, DateTime.Now, message);
}
Console.ForegroundColor = color;
Console.WriteLine("{0}", message);
Console.ResetColor();
}
I am instantiating this class and then calling logger.LogMessage("poop", Logger.LogLevel.High, false); and nothing is showing.
Thanks
The writes are being buffered in memory, try calling logFileStream.Flush(); at the end of each Log function.
You really shouldn't be keeping the file handle open between calls though, if I were you I would open and close it in each function. If you're doing a lot of logging then buffer it yourself in memory and dump the whole thing once it reaches a certain size.
This is the correct version of your example
use autoflush = true in stream writer
open/close stream in every request - if it is correctly implemented, autoflush is unnecessary (flush will be done after dispose StreamWriter)
use FileMode.Append
public class Logger
{
public enum LogLevel
{
Low,
Medium,
High
};
private readonly string _filePath;
public Logger(string filePath)
{
//logStream = new StreamWriter(logFilePath, false);
_filePath = filePath;
}
public void LogMessage(string message)
{
LogMessage(message, LogLevel.Low, false);
}
public void LogMessage(string message, LogLevel level, bool excludeFromLogFile)
{
using (var fileStream = new FileStream(_filePath, FileMode.Append, FileAccess.Write))
{
using (var writer = new StreamWriter(fileStream) {AutoFlush = true})
{
var prefix = string.Empty;
var color = ConsoleColor.White;
switch (level)
{
case LogLevel.Medium:
prefix = "?";
color = ConsoleColor.Yellow;
break;
case LogLevel.High:
prefix = "!";
color = ConsoleColor.Red;
break;
}
if (!excludeFromLogFile)
{
writer.WriteLine("{0} {1} {2}", prefix, DateTime.Now, message);
}
Console.ForegroundColor = color;
Console.WriteLine("{0}", message);
Console.ResetColor();
}
}
}
}
I'm writing a windows service (C#) that does a task repetitively. I'm using a thread to complete my requirement. Now I need to maintain a log file that keeps logs regarding the operation.
My service class is as follow
public partial class CPEService : ServiceBase
{
static ServiceBot bot = new ServiceBot();
static ProgramLog logger = new ProgramLog();//ProgramLog Object
private static bool state = true;
//private static int count = 1;
//private System.Timers.Timer timer;
public CPEService()
{
InitializeComponent();
}
internal void TestStartupAndStop()
{
Thread workerThread = new Thread(loopTrough);
workerThread.Start();
}
protected override void OnStart(string[] args)
{
Thread workerThread = new Thread(loopTrough);
workerThread.Start();
}
private void loopTrough()
{
logger.log("Thread fired");
while (state)
{
logger.log("Thread fired"); //This is not Working
bot.start();
Thread.Sleep(180000);
}
}
protected override void OnStop()
{
state = false;
}
}
I have a separate class call "ProgramLog" to handle all the log related operations.This is that class.
public class ProgramLog
{
string fileName = "";//Global variable to store file name
#region method to handle usual log records
public void log(string text)//create normal Log text
{
fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory+fileName))
{
using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine(text);
tw.Flush();
tw.Close();
fs.Close();
}
}
else
{
createFolder();
log(text);
}
}
#endregion
#region log Error record
public void logError(string text, string className,int LineNumber, string Stacktrace)//create error text
{
fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + fileName))
{
using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine("**************************ERROR****************************");
tw.WriteLine(text);
tw.WriteLine("In Class :{0}", className);
tw.WriteLine("In Line :{0}", LineNumber);
tw.WriteLine("ERROR :{0}",Stacktrace);
tw.WriteLine("***********************************************************");
}
}
else
{
createFolder();
logError(text,className,LineNumber,Stacktrace);
}
}
#endregion
#region create folder to store log files
public void createFolder()//create a folder for Log files
{
try
{
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Log"))
{
string folderName = "Log";
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + folderName);
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
StreamWriter sr = new StreamWriter(fs);
sr.Flush();
sr.Close();
fs.Close();
}
else
{
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
StreamWriter sr = new StreamWriter(fs);
sr.Flush();
sr.Close();
fs.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
#endregion
}
According to the above class, When I start the service it needs to create folder call "Log" where it does not exists, then it creates a text file inside that folder and lastly it starts to create the log entries.
Even though the thread is working correctly it never touches the "ProgramLog" methods. I checked by directly calling the method "loopTrough". then its working fine.
Please help me to resolve this bug.
Thank you
You declare a Thread workerThread = new Thread(loopTrough);, but you don't start this Thread. Just call workerThread.Start().
I want to receive input from command line when my device scans barocode and give barcode related information to the conmmand line on telnet window which we start from login in telnet server through cmd.exe by "telnet 192.168.x.x 23" and after typing this command in cmd then login succsessfull telnet window opens and and my machin connected to device , now I have to read barcode string from this window and display output related to that string. please give me any idea how to do this?
here is my code which simply manually enter input string and after pressing enter gives output.
namespace ConsoleApplication2
{
class Program
{
private static System.Timers.Timer aTimer;
string path = #"C:\Users\Priya\Desktop\Project\barcode.txt";
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SaiNathHospital"].ToString());
public void getConsoleInput()
{
try
{
FileInfo fi = new FileInfo(path);
for (int i = 0; i <= 0; i++)
{
Console.WriteLine("");
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(Console.ReadLine());
sw.Close();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public void getConsoleInputAtRuntime()
{
}
public void ReadWriteIntoFile()
{
try
{
string filename = #"C:\Users\Priya\Desktop\Project\Data.txt";
StringBuilder sb = new StringBuilder();
StreamReader sr = new StreamReader(path);
string s = sr.ReadLine();
sr.Close();
DataExport("Select * from PATIENT_TABLE where [BARCODE] = '" + s + "'", filename);
}
catch { }
}
public void DataExport(string SelectQuery, string filename)
{
try
{
using (var dt = new DataTable())
{
using (var da = new SqlDataAdapter(SelectQuery, con))
{
da.Fill(dt);
var rows =
from dr in dt.Rows.Cast<DataRow>()
select String.Join(
",",
from dc in dt.Columns.Cast<DataColumn>()
let t1 = Convert.IsDBNull(dr[dc]) ? "" : dr[dc].ToString()
let t2 = t1.Contains(",") ? String.Format("\"{0}\"", t1) : t1
select t2);
using (var sw = new StreamWriter(filename))
{
// sw.WriteLine(header);
foreach (var row in rows)
{
sw.WriteLine(row);
}
sw.Close();
}
}
}
}
catch (Exception e) { Console.WriteLine(e.Message); }
}
public void WriteFileOutput()
{
string path = #"C:\Users\Priya\Desktop\Project\Data.txt";
if (File.Exists(path))
{
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
Console.ReadLine();
}
public void timer()
{
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 10000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.\n");
Console.ReadLine();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//System.Windows.Forms.SendKeys.Send("{ENTER}");
Console.WriteLine("5 seconds Elapsed at {0} ", e.SignalTime); // for your reference to check every five seconds
}
public static void Main(string[] args)
{
Program p = new Program();
p.getConsoleInput();
p.ReadWriteIntoFile();
p.WriteFileOutput();
}
}
}
Priyanka, welcome to SO. The approach I would take towards this would be to programatically issue the telnet and wait for the response from the telnet. Now since, you are logging in the ConsoleApplication2 is not aware of the session.
So, here is the high level approach towards the solution
Launch your ConsoleApplication2 application
Use a Telnet library to open the connection towards the device
Read the response of scan from the Telnet using the same library
Do the database thing with the response.
The problem will become simpler if you have a Telnet library. However, there is a similar question in SO and a library which was recommended here - Executing commands by using Telnet in C#
Hope this helps!