Exception guidance [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Throwing an exception on this line:
AnnuityReader.WriteLine(fields[0] + "," + fields[1] + "," + fields[3] + "," + fields[4]);
I know there are some similar posts out here which have been resolved, but I have not figured it out yet. Any input is appreciated.
InitializeComponent();
}
StreamWriter AnnuityReader;
List<string[]> Accounts = new List<string[]>();
private int x;
private void Assignment2_Load(object sender, EventArgs e)
{
string currentLine;
string[] fields = new string[2];
//Create streamreader
StreamReader AnnuityReader = new StreamReader("annuities.txt");
while (AnnuityReader.EndOfStream == false)
{
currentLine = AnnuityReader.ReadLine();
fields = currentLine.Split(',');
Accounts.Add(fields);
cmbAccount.Items.Add(fields[0]);
}
AnnuityReader.Close(); //Creates dictionary
}
private void cmbAccount_SelectedIndexChanged(object sender, EventArgs e)
{
lstAccountDetails.Items.Clear();
int index = cmbAccount.SelectedIndex;
string[] fields;
fields = Accounts[index];
lstAccountDetails.Items.Add(String.Format("{0,10} {1,10}{2,10}", "Rate", "Deposit($)", "Value($)"));
lstAccountDetails.Items.Add(String.Format("{0,10} {1,10:C}{2,10:C}", fields[1], double.Parse(fields[2]), double.Parse(fields[4])));
}
private void btnProcess_Click(object sender, EventArgs e)
{
lstAccountDetails.Items.Clear();
double deposit;
int index = cmbAccount.SelectedIndex;
string[] fields = Accounts[index];
try
{
deposit = double.Parse(txtDeposit.Text);
}
catch
{
MessageBox.Show("Enter a positive number");
txtDeposit.SelectAll();
txtDeposit.Focus();
return;
}
double currentValue = double.Parse(fields[4]);
if (deposit > 0)
{
currentValue += deposit;
}
else
MessageBox.Show("Please enter a positive number");
fields[4] = currentValue.ToString();
fields = Accounts[x];
AnnuityReader.WriteLine(fields[0] + "," + fields[1] + "," + fields[3] + "," + fields[4]);
lstAccountDetails.Items.Add(String.Format("{0,10} {1,10}{2,10}", "Rate", "Deposit($)", "Value($)"));
lstAccountDetails.Items.Add(String.Format("{0,10} {1,10:C}{2,10:C}", fields[1], double.Parse(fields[2]), double.Parse(fields[4])));
txtDeposit.Clear();
AnnuityReader.Close();
}

Error is pretty clear. Object reference not set to an instance of an object. You are defining StreamWriter AnnuityReader but you are using that reference without setting to an object in btnProcess_Click function.
You can solve it in two ways. You need to set it to an instance in constructor or in your btnProcess_Click function before using. You can set it to an object like you did in Assignment2_Load function.
StreamReader AnnuityReader = new StreamReader("annuities.txt");

Related

Filename overwrites the uploaded attachments

The file name is generated by Po+Invoice in the sql table. When user attach a pdf it overwrites the existing file name that has same po+invoice. Is there anyway i could create the unique id filename.
public partial class upload : System.Web.UI.Page
{
string mID;
DataBaseDataContext dataBaseDataContext = new DataBaseDataContext();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnExit_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void SUbmit(object sender, EventArgs e)
{
try
{
var ext = FileUploadtoServer.FileName.Substring(FileUploadtoServer.FileName.IndexOf('.') + 1, 3);
if (ext.ToLower() != "pdf")
{
Response.Write("<script>alert('Please select a pdf File!')</script>");
return;
}
}
catch (Exception ex)
{
Response.Write("<script>alert('Please select a pdf File!')</script>");
return;
}
if (PO_Number.Text.Equals("") || HeadCode.Text.Equals("") || Manufacture.Text.Equals("") || Description.Text.Equals("") || Invoice.Text.Equals(""))
{
Response.Write("<script>alert('Please Fill All Fields!')</script>");
}
TPT tPT = new TPT();
tPT.Invoice_No = Invoice.Text;
tPT.PO_Number = PO_Number.Text;
tPT.Item_Code = Manufacture.Text;
tPT.Heat_Code = HeadCode.Text;
tPT.Description = Description.Text;
tPT.FileName = PO_Number.Text + Invoice.Text + ".pdf";
dataBaseDataContext.TPTs.InsertOnSubmit(TPT);
dataBaseDataContext.SubmitChanges();
String path = Server.MapPath("Attachments/" + PO_Number.Text + Invoice.Text + ".pdf");
FileUploadtoServer.SaveAs(path);
Response.Write("<script>alert('Successfully Inserted!')</script>");
Invoice.Text = "";
Manufacture.Text = "";
HeadCode.Text = "";
Description.Text = "";
PO_Number.Text = "";
}
}
I have tried
Guid.NewGuid() + ".pdf";,
it still does the same thing.
The simple way would be to just take the file name, and add -1, then -2, then -3
So,
mydoc.pdf
mydoc-1.pdf
mydoc-2.pdf
etc. etc.
So, then say a function like this:
Edit: Updated code
string GetServerFilenext(string strFileFullPath)
{
string strFileToCheck = "";
for (int i = 0; i < 100; i++)
{
if (i == 0)
strFileToCheck = strFileFullPath;
else
strFileToCheck =
Path.GetDirectoryName(strFileFullPath) +
#"\" + Path.GetFileNameWithoutExtension(strFileFullPath) +
"-" + i.ToString() + Path.GetExtension(strFileFullPath);
if (!File.Exists(strFileToCheck))
break;
}
return strFileToCheck;
}
So, now your code becomes this:
string sFileToSave =
Server.MapPath(#"~/Attachments/" + PO_Number.Text + Invoice.Text + ".pdf");
sFileToSave = GetServerFileNext(sFileToSave);
tPT.FileName = Path.GetFileName(sFiletoSave);
So, you setup the full path and file name.
You then check if it exists, and if not, then add -1, then -2 etc. etc.
Edit2: So, code would look like this (warning: air code)
string sFileToSave =
Server.MapPath(#"~/Attachments/" + PO_Number.Text + Invoice.Text + ".pdf");
sFileToSave = GetServerFileNext(sFileToSave);
TPT tPT = new TPT();
tPT.Invoice_No = Invoice.Text;
tPT.PO_Number = PO_Number.Text;
tPT.Item_Code = Manufacture.Text;
tPT.Heat_Code = HeadCode.Text;
tPT.Description = Description.Text;
tPT.FileName = Path.GetFileName(sFileToSave);
dataBaseDataContext.TPTs.InsertOnSubmit(TPT);
dataBaseDataContext.SubmitChanges();
FileUploadtoServer.SaveAs(sFileToSave);
Instead of adding -1,-2, i was able to upload it by adding date stamp
`tPT.FileName = PO_Number.Text + Invoice.Text + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";`

Accessing Variables by multiple threads in web application [duplicate]

This question already has an answer here:
Asp.net losing values of variables
(1 answer)
Closed 4 years ago.
I am running a web Form where I call a new thread on a button press to execute an Rdotnet snippet of code ( I needed the thread because the current thread kept sending stack overload errors ).
In the Rdotnet function , I have it access a global class variable and put data into it. Once the function completes and the button submit function is over I try to access that global class on another button click ( separate button ), however it is empty. I assume that the thread ends so all data in it ends to, so I tried returning the class and putting it into the global variable in the buttonclick function itself,same result.
I need help.
public partial class BTForm : Page
{
List<DirectorDetail> Details = new List<DirectorDetail>();
BindingList<string> Test = new BindingList<string>();
List<string> Line = new List<string>();
List<string> output = new List<string>();
WebDetails BTlibrary;
OpenFileDialog ofd = new OpenFileDialog();
List<string> Months = new List<string>();
List<string> Year = new List<string>();
BTBill Billfile = new BTBill();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
addMonth();
addyear();
foreach (var x in Months)
{
DropDownList1.Items.Add(x);
}
foreach (var y in Year)
{
DropDownList2.Items.Add(y);
}
}
try
{
ListBox4.DataSource = Test;
ListBox4.DataBind();
}
catch(Exception x)
{
Console.Write(x);
}
}
protected void Submit_Click(object sender, EventArgs e)
{
Thread current = Thread.CurrentThread;
WebDetails BTlibrary2 =BTlibrary;
Thread t = new Thread(() => { BTlibrary2 = processes(BTlibrary2); }, 2500000);
t.Start();
t.Join();
BTlibrary = BTlibrary2;
// Thread.Sleep(10000);
}
public WebDetails processes(WebDetails library)
{
if (FileUpLoad1.HasFile)
{
string location = #"C:/BTBill/" + FileUpLoad1.FileName;
Billfile.Tablename = FileUpLoad1.FileName;
try
{
Billfile.Month = DropDownList1.SelectedItem.ToString();
Billfile.Year = DropDownList2.SelectedItem.ToString();
Billfile.Filename = Cleaning.PathCleaning(location);
Billfile.Limit = TextBox3.Text.ToString();
string fpath = Billfile.Month + " " + Billfile.Year + " Query " + "Limit -£ " + Billfile.Limit + "\\";
string filename = Billfile.Month + " " + Billfile.Year + " Query " + "Limit -£ " + Billfile.Limit;
Billfile.Savelocation = "//lonvmfs01/commonwealth_Data/BT BILL Alert/" + filename;
Billfile.Sfilename = "//lonvmfs01/commonwealth_Data/BT BILL Alert/" + filename;
}
catch (Exception x)
{
Error1.Text = "Please Select Month and year\nERROR : " + x;
}
FileUpLoad1.SaveAs(#"C:\BTBill\" + FileUpLoad1.FileName);
library = Executable.executable(Billfile);
// FileUpLoad1.
// = "File Uploaded: " + FileUpLoad1.FileName;
}
else
{
Label1.Text = "No File Uploaded.";
}
DataFrame Director = library.Director;
DataFrame bill = library.Query;
DataFrame limit = library.Btlim;
int colcount = Director.RowCount;
for (int x = 0; x < colcount; x++)
{
string cost_centre = Director[x, 0].ToString();
string director = Director[x, 1].ToString();
string email_address = Director[x, 2].ToString();
double total = SendMail.calculatetotal(bill, limit, cost_centre);
if (total > 0)
{
Line.Add(x + " )\t" + cost_centre + "\t" + director + "\t\t" + email_address + "\t" + total);
Test.Add(x + " )\t" + cost_centre + "\t" + director + "\t\t" + email_address + "\t" + total);
}
}
ListBox4.DataSource = Test;
ListBox4.DataBind();
//foreach (var x in getline().ToArray())
// {
// ListBox4.Items.Add(x);
// }
// ListBox4.DataBind();
return library;
}
protected void Sendmail(object sender, EventArgs e)
{
DataFrame Director = BTlibrary.Director;
DataFrame bill = BTlibrary.Query;
DataFrame limit = BTlibrary.Btlim;
string test;
foreach (Object selecteditem in ListBox4.GetSelectedIndices() )
{
test = ListBox4.Items[(int)selecteditem].Text;
System.Diagnostics.Debug.WriteLine(test);
test = test.Substring(0, 1);
output.Add(test);
}
List<int> index = new List<int>();
for (int y = 0; y < output.Count; y++)
{
index.Add(Convert.ToInt32(output[y]));
}
for (int y = 0; y < index.Count; y++)
{
DirectorDetail temp = new DirectorDetail();
temp.cost_centre = Director[index[y], 0].ToString();
temp.director = Director[index[y], 1].ToString();
temp.email_address = Director[index[y], 2].ToString();
for (int count = 0; count < limit.RowCount; count++)
{
if (limit[count, 0].ToString() == temp.cost_centre)
{
temp.limit = limit[count, 1].ToString();
}
}
Details.Add(temp);
}
SendMail.Mailing(BTlibrary.Query, BTlibrary.Deplist, BTlibrary.Btlim, BTlibrary.Bill, Details);
//Session["Details"] = Details;
// this.Close();
}
private void addyear()
{
DateTime time = System.DateTime.UtcNow;
int baseyear = time.Year - 3;
for (int x = baseyear; x < (baseyear + 10); x++)
{
Year.Add(x.ToString());
}
}
// returns the list of years
public List<string> getYear()
{
return Year;
}
// returns the list of months
public List<String> getMonth()
{
return Months;
}
//adds months to a list
private void addMonth()
{
Months.Add("January");
Months.Add("February");
Months.Add("March");
Months.Add("April");
Months.Add("May");
Months.Add("June");
Months.Add("July");
Months.Add("August");
Months.Add("September");
Months.Add("October");
Months.Add("November");
Months.Add("December");
}
public List<string> getline()
{
return Line;
}
}
public static WebDetails executable(BTBill bill)
{
StartupParameter rinit = new StartupParameter();
rinit.Quiet = true;
rinit.RHome = #"C:\Program Files\R\R-3.4.4\";
rinit.Home = #"C:\R";
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance(null,true,rinit);
// engine.Initialize();
//install and make connection to Postgres
// engine.Evaluate("install.packages('RPostgreSQL') \n install.packages('gridExtra')");
engine.Evaluate("require('RPostgreSQL')" + "\n" +
"pw <- {'admin'}" + "\n" +
"drv <- RPostgreSQL::PostgreSQL()" + "\n" +
"drv <- dbDriver('PostgreSQL')" +"\n"+
"con <- dbConnect(drv, dbname = 'postgres'," +"\n"+
"host = 'localhost', port = 5432," +"\n"+
"user = 'postgres', password = pw)");
engine.Evaluate("postgresmfile<- dbGetQuery(con,'select * from masterfile')" + "\n" +
"Contact <- dbGetQuery(con, 'select * from contact')"+"\n"+
"btlim<- dbGetQuery(con, ' select * from bt_departmentlimit')"+"\n"+
"dbDisconnect(con)");
engine.Evaluate("BTBill = read.csv(file<-'"+bill.Filename+"', header=TRUE, sep=',',skip=1)");
// building dataframes and queries
DataFrame BTBill = engine.Evaluate("BTBill").AsDataFrame();
DataFrame MasterFile = engine.Evaluate("postgresmfile").AsDataFrame();
DataFrame BTLim = engine.Evaluate("btlim").AsDataFrame();
DataFrame Contact= engine.Evaluate("Contact ").AsDataFrame();
DataFrame Query = engine.Evaluate("Merged <- merge(BTBill,postgresmfile,by.x='SERVICE.NO',by.y = 'service_number')" + "\n"+ "Merged_2 <- merge(Merged,Contact,by.x='cost_centre',by.y='cost_centre') " + "\n"+
"query <- Merged_2[c('SERVICE.NO','username','cost_centre','job_post','USAGE.CHARGES','TOTAL.COST','USAGE.START.DATE','USAGE.END.DATE','director','email_address')]").AsDataFrame();
DataFrame Merge2 = engine.Evaluate("Merged_2").AsDataFrame();
DataFrame maillist = engine.Evaluate("data.frame(query)" +"\n"+
"test <-subset(query, TOTAL.COST >= "+bill.Limit+ ", select = c(SERVICE.NO,username,cost_centre,job_post, TOTAL.COST, USAGE.START.DATE, USAGE.END.DATE,director,email_address,USAGE.CHARGES))").AsDataFrame();
DataFrame DepList = engine.Evaluate("x<-test[c('cost_centre','director','email_address')]" + "\n" +
"ux<-unique(x) ").AsDataFrame();
DataFrame DepList2=engine.Evaluate("y <-query[c('cost_centre', 'director', 'email_address')]" + "\n" +
"uy<-unique(y) ").AsDataFrame();
engine.Evaluate("dir.create(file.path('" + bill.Savelocation + "'))");
//creating pdf files for each department head
engine.Evaluate("write.csv(Merged_2, file = '" + bill.Savelocation + "/MasterFile.csv');");
for (int count = 0; count < DepList.RowCount; count++)
{
DataFrame temp = engine.Evaluate("data.frame(query);" +
"test2 <-subset(query, USAGE.CHARGES >= " + bill.Limit + " & cost_centre=='"+DepList[count,0]+"', select = c(SERVICE.NO,username,cost_centre,job_post, USAGE.CHARGES, USAGE.START.DATE, USAGE.END.DATE,director,email_address))").AsDataFrame();
engine.Evaluate("library(gridExtra);");
engine.Evaluate("pdf('" + bill.Sfilename +"/"+ DepList[count, 0] + ".pdf', height=20, width=20);" );
try
{
engine.Evaluate("grid.table(test2); dev.off() ;");
}
catch (Exception e)
{
}
}
SendMailForm form = new SendMailForm();
WebDetails web = new WebDetails(DepList2, Query, BTLim);
web.Deplist = DepList;
web.Bill = bill;
engine.Evaluate("write.csv(test, file = '" + bill.Savelocation + "/Users over threshold.csv')");
engine.Dispose();
return web;
// form.Director=DepList2;
//form.bill = Query;
//form.limit = BTLim;
List<DirectorDetail> output = form.Details;
SendMail.Mailing(Query, DepList,BTLim, bill,output);
// to filter by department
// DataFrame maillist = engine.Evaluate("data.frame(query)" + "\n" +
// "test <-subset(query, TOTAL.COST >= " + bill.Limit + "& Cost.Centre=='"+bill.Dep+"', select = c(SERVICE.NO, User.Name, Cost.Centre, ROLE.JOB.POST, TOTAL.COST, USAGE.START.DATE, USAGE.END.DATE,DIRECTOR,EMAIL.ADDRESS))").AsDataFrame();
//engine.Evaluate("install.package('dplyr')");
}
}
}
It seems my problem turned out to be unrelated to variable sharing through threads, but instead to deal with the way button click instances worked.
long story short, in order to share a variable between two event instances, the easiest way to do it is through Sessions.
I needed to put the BTlibrary in a session and access it in the second button click event for it to get the value saved from the previous.
protected void Submit_Click(object sender, EventArgs e)
{
Thread current = Thread.CurrentThread;
WebDetails BTlibrary2 =BTlibrary;
Thread t = new Thread(() => { BTlibrary2 = processes(BTlibrary2); }, 2500000);
t.Start();
t.Join();
Session["BTLib"] = BTlibrary2;
// Thread.Sleep(10000);
}
protected void Sendmail(object sender, EventArgs e)
{
List<DirectorDetail> Details = new List<DirectorDetail>();
BTlibrary = (WebDetails) Session["BTLib"];
this worked

Putting a Struct in a Dictionary [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
i want to use a struct in a dictionary its key is a string and the value is the struct. i don't know what's the syntax as i'm new to c# i was writing c++ before.
BTW i want to read from a text file and put the lines in the dictionary.
here's what i did already:
public class CDinfo
{
public string code;
public string type;
public int count;
}
private void button1_Click(object sender, EventArgs e)
{
string pathsource = #"F:\Computer Science\CD & Instruments\CDs.txt";
CDinfo lolo = new CDinfo();
string name;
name = textBox1.Text;
lolo.type = textBox2.Text;
lolo.code = textBox3.Text;
lolo.count = int.Parse(count.Text);
Dictionary<string, CDinfo> MS = new Dictionary<string, CDinfo>();
StreamReader reader = new StreamReader(pathsource);
while (reader.Peek() != -1)
{
string m;
string[] fasl;
m = reader.ReadLine();
fasl = m.Split(',');
lolo.type = fasl[1];
lolo.code = fasl[2];
lolo.count = fasl[3];
MS.Add(fasl[0], lolo);
}
reader.Close();
StreamWriter sw = new StreamWriter(pathsource, append: true);
string s = name + ',' + lolo.type + ',' + lolo.code + ',' + lolo.count;
sw.WriteLine(s);
sw.Close();
MessageBox.Show("CD Added Successfully.");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
After running the solution i'm getting this error "Index was outside the bounds of the array".
You are initializing a new dictionary every time you click Button1, and you are not keeping track of it, so you will never be able to use it from a different context. You need to defined your dictionary as a class variable, and add a value to it from inside your click method:
Dictionary<string, CDinfo> MS = new Dictionary<string, CDinfo>(); // initialize the dictionary somewhere outside of your click handler
private void button1_Click(object sender, EventArgs e)
{
CDinfo lolo = new CDinfo();
string name;
name = textBox1.Text;
lolo.type = textBox2.Text;
lolo.code = textBox3.Text;
lolo.count = int.Parse(count.Text);
// add to the dictionary here
MS.Add(name, lolo);
}
Also, as some of the comments have already mentioned, CDinfo should probably be a class, not a struct.

Why am I getting the Exception Object reference not set to an instance of an object [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
What does "Object reference not set to an instance of an object" mean? [duplicate]
(8 answers)
Closed 8 years ago.
I have the following method:
public string GetReadersAsListXML()
{
StringBuilder sbXML = new StringBuilder();
sbXML.Append("<items>" + "\r\n");
string filePath = ConfigurationManager.AppSettings["RFIDScannerConfiguration"];
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;
using (XmlReader reader = XmlReader.Create(filePath, readerSettings))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.LocalName == "add")
{
int ListenerNumber = 1;
string Key = reader.GetAttribute("key");
Key = Key.Remove(Key.Length - 3);
string Value = reader.GetAttribute("value");
if (Key == "Active")
{
sbXML.Append("<item>" + "\r\n");
sbXML.Append("<id>Listener" + ListenerNumber + "</id>" + "\r\n");
sbXML.Append("<attributes>" + "\r\n");
ListenerNumber++;
}
sbXML.Append("<attribute>" + "\r\n");
sbXML.Append("<code>" + Key + "</code>" + "\r\n");
sbXML.Append("<value><![CDATA[" + Value + "]]></value>" + "\r\n");
sbXML.Append("</attribute>" + "\r\n");
}
}
}
}
return sbXML.ToString();
}
Which I am using to parse an XML file.
I want to remove the last 3 characters of the string 'Key'.
However, I am getting the following error:
'Object reference not set to an instance of an object'.
I have used the .remove method in exactly the same way previously and it worked fine.
I know it is the line:
Key = Key.Remove(Key.Length - 3);
Causing the problem, but why, it is setup properly?
Does the Key is not null? Certainly it is null. Hence you get this error.
In order to avoid this check this before you Remove that you want:
if(Key!=null && Key.Length>3)
Key = Key.Remove(Key.Length - 3);

How to keep logs in C#?

This is a WinForm written in C#.
Lets say I'm generating a random named text file in my selected directory. When the button is clicked teh first time, i write the data contained in the textboxes into that text file. If the user wants to do the same thing with different data in the textboxes then the click on the button should write the new data into the text file without losing the old data. It's like keeping logs, is this possible?
My code is like:
private readonly Random setere = new Random();
private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString()
{
char[] buffer = new char[5];
for (int i = 0; i < 5; i++)
{
buffer[i] = chars[setere.Next(chars.Length)];
}
return new string(buffer);
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dia == DialogResult.Yes)
{
StreamWriter wFile = new StreamWriter("C:\\Users\\Ece\\Documents\\Testings\\" + RandomString() + ".txt");
wFile.WriteLine("Name Surname:" + text1.Text + text2.Text);
wFile.WriteLine("Other:" + text3.Text + text4.Text);
wFile.WriteLine("Money:" + textBox1.Text + " TL.");
wFile.WriteLine("*************************************");
wFile.Close();
}
else
{
return;
}
}
You can append to the text in the file.
See
File.AppendText
using (StreamWriter sw = File.AppendText(pathofFile))
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
where pathofFile is the path to the file to append to.
Have a look at using something like this:
StreamWriter fw = new StreamWriter(#"C:\Logs\MyFile.txt",true);
fw.WriteLine("Some Message" + Environment.Newline);
fw.Flush();
fw.Close();
Hope that helps. See MSDN StreamWriter for more information
Updated: Removed old example
Also if you are trying to create a unique file you can use Path.GetRandomFileName()
Again from the MSDN Books:
The GetRandomFileName method returns a
cryptographically strong, random
string that can be used as either a
folder name or a file name.
UPDATED: Added a Logger class example below
Add a new class to your project and add the following lines (this is 3.0 type syntax so you may have to adjust if creating a 2.0 version)
using System;
using System.IO;
namespace LogProvider
{
//
// Example Logger Class
//
public class Logging
{
public static string LogDir { get; set; }
public static string LogFile { get; set; }
private static readonly Random setere = new Random();
private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public Logging() {
LogDir = null;
LogFile = null;
}
public static string RandomFileName()
{
char[] buffer = new char[5];
for (int i = 0; i < 5; i++)
{
buffer[i] = chars[setere.Next(chars.Length)];
}
return new string(buffer);
}
public static void AddLog(String msg)
{
String tstamp = Convert.ToString(DateTime.Now.Day) + "/" +
Convert.ToString(DateTime.Now.Month) + "/" +
Convert.ToString(DateTime.Now.Year) + " " +
Convert.ToString(DateTime.Now.Hour) + ":" +
Convert.ToString(DateTime.Now.Minute) + ":" +
Convert.ToString(DateTime.Now.Second);
if(LogDir == null || LogFile == null)
{
throw new ArgumentException("Null arguments supplied");
}
String logFile = LogDir + "\\" + LogFile;
String rmsg = tstamp + "," + msg;
StreamWriter sw = new StreamWriter(logFile, true);
sw.WriteLine(rmsg);
sw.Flush();
sw.Close();
}
}
}
Add this to your forms onload event
LogProvider.Logging.LogDir = "C:\\Users\\Ece\\Documents\\Testings";
LogProvider.Logging.LogFile = LogProvider.Logging.RandomFileName();
Now adjust your button click event to be like the following:
DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dia == DialogResult.Yes)
{
StringBuilder logMsg = new StringBuilder();
logMsg.Append("Name Surname:" + text1.Text + text2.Text + Environment.NewLine);
logMsg.Append("Other:" + text3.Text + text4.Text + Environment.NewLine);
logMsg.Append("Money:" + textBox1.Text + " TL." + Environment.NewLine);
logMsg.Append("*************************************" + Environment.NewLine);
LogProvider.Logging.AddLog(logMsg.ToString());
} else
{
return;
}
Now you should only create one file for the entire time that application is running and will log to that one file every time you click your button.
You might want to take a look at log4net and the RollingFileAppender
Sure. Just open the file for appending with something like System.IO.File.AppendText

Categories