This question already has answers here:
Open existing file, append a single line
(9 answers)
Closed 4 years ago.
Basicly I'm writing a fake malware, which will write in a .txt the Session username of the person which clicked on it. The problem is that when someone execute it will erase the previous lines.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "Fake Malware";
}
private void Form1_Load(object sender, EventArgs e)
{
string createText = " just clicked on the fake Malware";
File.WriteAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName + createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
private void zig(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("Link to a warning message on click, nothing important.");
string createText = " just clicked on the fake Malware";
File.WriteAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName+ createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
}
I think what you are looking for is AppendAllText:
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", "Wow it worked :)");
Here is the fix
private void Form1_Load(object sender, EventArgs e)
{
string createText = " just clicked on the fake Malware";
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName + createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
private void zig(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("#");
string createText = " just clicked on the fake Malware";
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName+ createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
}
}
Related
I'm making a program that can save data from one combobox and two textboxes. When open the program, the saved data (in textfile) should open automaticly in Combobox with the text that was saved as a textfile. Also there should be one open-button that can open another textfile (if someone did a backup), and a delete button that can delete the selected "data" that is selected in the combobox.
With other words, if I save "Combobox: test 1", "Textbox1: test 2", "Textbox: test 3", and then save another data "Combobox: test a", "Textbox1: test b", "Textbox: test c".
When restarting the program, Combobox should have "test 1" and "test a" that can be choosed from.
The only feature I can get to work is saving the txt-file, but only open all text on the same row (witch I do not want). If this is impossible with the txt-file, It also works if someone can show me how to do this with a XML-file instead.
using System.IO;
namespace openclose
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string nl = "\r\n";
TextWriter txt = new StreamWriter("test.txt");
txt.Write((comboBox1.Text) + nl + (textBox1.Text) + nl + (textBox2.Text));
txt.Close();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = File.ReadAllText("test.txt");
textBox2.Text = File.ReadAllText("test.txt");
comboBox1.Text = File.ReadAllText("test.txt");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
I did also try to change the "savebutton" with this instead, it does save. But I can't figure out how to make the saved data show upp in the combobox so I can get back the data to textbox1 and textbox2.
string path = #"Test.txt";
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "";
File.WriteAllText(path, createText, Encoding.UTF8);
}
string appendText = comboBox1.Text + Environment.NewLine + textBox1.Text + Environment.NewLine + textBox2.Text + Environment.NewLine;
File.AppendAllText(path, appendText, Encoding.UTF8);
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
private void button1_Click(object sender, EventArgs e)
{
try
{
var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
WriteToFile.Close();
this.Close();
}
catch (System.IO.DirectoryNotFoundException ex)
{
//add error message
}
}
private void button3_Click(object sender, EventArgs e)
{
File.AppendAllText("student.txt", "\r\n" + txtStudNum.Text + ", " +
txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
}
private void button4_Click(object sender, EventArgs e)
{
}
I want to calculate the average for txtModMark from the textfile once all the values have been entered. It will go under button 4 so when I click it, it calculates. I need to know how to skip the first few columns per row and get to the last column to perform the average calculation.
What's the point in reading from file then parse it and then convert to INT and then calculate average when you can do it directly using s List<int> like below:
declare a List<int> in your Form
List<int> marks = new List<int>();
Store the marks in button click event
private void button1_Click(object sender, EventArgs e)
{
try
{
var WriteToFile = new System.IO.StreamWriter("student.txt"); //create textfile in default directory
WriteToFile.Write(txtStudNum.Text + ", " + txtStudName.Text + ", " + txtModCode.Text + ", " + txtModMark.Text);
WriteToFile.Close();
marks.Add(Convert.ToInt32(txtModMark.Text)); //add to list
}
catch (System.IO.DirectoryNotFoundException ex)
{
//add error message
}
}
In button4 click event calculate the average
private void button4_Click(object sender, EventArgs e)
{
int totalmarks = 0;
foreach(int m in marks)
totalmarks += m;
MessageBox.Show("Average Is: " + totalmarks / marks.Count);
}
In my program, when I click a particular row in DataGridView, if that row contains "\" it should pop up an error message that "\ is not allowed in name or in path". I don't know how to do that.
Here is the code:
namespace OVF_ImportExport
{
public partial class Form1 : Form
{
string sName = "";
string sPath = "";
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
sName = row.Cells[0].Value.ToString();
sPath = row.Cells[1].Value.ToString();
}
}
private void BtnCreate_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
StreamWriter file = new StreamWriter("Export.bat");
file.WriteLine("c: ");
file.WriteLine("cd \\");
file.WriteLine("cd Program Files ");
file.WriteLine("cd VMware");
file.WriteLine("cd VMware OVF Tool");
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
sName = row.Cells[0].Value.ToString();
sName = sName.Trim();
sPath = row.Cells[1].Value.ToString();
file.WriteLine("start ovftool.exe --powerOffSource vi://" + TxtUsername.Text + ":" + TxtPassword.Text + "#"
+ TxtIP.Text + sPath + " " + "\"" + TxtBrowsepath.Text + "\\" + sName + "\\" + sName + ".ovf" + "\"" + Environment.NewLine);
}
file.WriteLine("pause");
MessageBox.Show("Batch File Created","Batch File");
file.Close();
}
try using this:
// Attach DataGridView events to the corresponding event handlers.
this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
method for above event handler:
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
{
if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"Company Name must not be empty";
e.Cancel = true;
}
}
}
In the following I've taken out irrelevant code. I've created a field called printString. The calculateButton_Click method does a heap of stuff, then I want to send it to a print-friendly page using response.write. However the printString variable doesn't seem to ever stop being "DEFAULT". DEFAULT is all that shows up on my blank page when I click the printButton_Click. Trimmed code below:
public partial class _Default : System.Web.UI.Page
{
private string _printString = "DEFAULT";
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
}
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
}
When printButton is clicked it is using the value DEFAULT from when the variable is being set.
private string _printString = "DEFAULT";
Is your problem. You need to maintain the state of printString when the variable is modified. Simply assigning _printString to another value is not persisting the change. You could either write a function to assign _printString to the correct value when printButton is clicked, use ViewState or Session or assign _printString in the printButton click function directly as shown below.
protected void printButton_Click(object sender, EventArgs e)
{
_printString = "Harry Potter";
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
Will result in Harry Potter being wrote to the page.
To use Session:
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["PrintString"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
_printString = (string)Session["PrintString"];
Response.Clear();
Response.Write(_printString);
Response.Flush();
Response.End();
}
ViewState:
ViewState["PrintString"] = "HarryPotter";
Then to retrieve the value you can simply do:
_printString = (string)ViewState["PrintString"];
http://msdn.microsoft.com/en-gb/library/ms972976.aspx
All (instance) variables are disposed at the end of the page's lifecycle since HTTP is stateless(even the controls). You could use a ViewState, HiddenField or Session variable instead.
private string PrintString
{
get
{
if (ViewState["PrintString "] == null || string.IsNullOrEmpty((String)ViewState["PrintString"]))
{
ViewState["PrintString"] = "DEFAULT";
}
return ViewState["PrintString"].ToString();
}
set { ViewState["PrintString"] = value; }
}
There are other options:
Nine Options for Managing Persistent User State in Your ASP.NET Application
The button click event is causing a postback and the _printString value is not being persisted. You need to store it in the calculate method via Session or Viewstate and then set it in the print for example: -
protected void calculateButton_Click(object sender, EventArgs e)
{
_printString = "";
_printString = "HARRY POTTER™: THE EXHIBITION Invoice<BR>Today's date: " + DateTime.Today.ToString("dd/MM/yyyy") + "<BR>Visit date: " +
dateSelectedString + "<BR><BR><BR>Adult tickets: " + numAdult + "<BR>Child tickets: " + numChild + "<BR>Family Passes: " + numFamily +
"<BR>Payment method: " + paymentType + "<BR>Total to pay: $" + totalPrice.ToString("0.00");
Session["bigstring"] = _printString;
}
protected void printButton_Click(object sender, EventArgs e)
{
Response.Clear();
_printString = Session["bigstring"].ToString();
Response.Write(_printString);
Response.Flush();
Response.End();
}
I have 2 buttons and I read different files when I click on these buttons. I used the to display the readfile using MsgBox since the files are big, so i want to display it in a richTextBox.
How can I open a richTextBox and display the read file when I click on any one of these buttons???
private void button1_Click(object sender, EventArgs e)
{
DisplayFile(FileSelected);//DisplayFile is the path of the file
var ReadFile = XDocument.Load(FileSelected); //Read the selected file to display
MessageBox.Show("The Selected" + " " + FileSelected + " " + "File Contains :" + "\n " + "\n " + ReadFile);
button1.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
FileInfo file = (FileInfo)comboBox2.SelectedItem;
StreamReader FileRead = new StreamReader(file.FullName);
string FileBuffer = FileRead.ReadToEnd(); //Read the selected file to display
//MessageBox.Show("The Selected" + " " + file + " " +"File Contains :" + "\n " + "\n " + FileBuffer);
// richTextBox1.AppendText("The Selected" + " " + file + " " + "File Contains :" + "\n " + "\n " + FileBuffer);
//richTextBox1.Text = FileBuffer;
}
Is there any other way to do it?
Here is a simple example (code based form design). It's better if you create the form via the GUI designer:
private void button1_Click(object sender, EventArgs e)
{
//test call of the rtBox
ShowRichMessageBox("Test", File.ReadAllText("test.txt"));
}
/// <summary>
/// Shows a Rich Text Message Box
/// </summary>
/// <param name="title">Title of the box</param>
/// <param name="message">Message of the box</param>
private void ShowRichMessageBox(string title, string message)
{
RichTextBox rtbMessage = new RichTextBox();
rtbMessage.Text = message;
rtbMessage.Dock = DockStyle.Fill;
rtbMessage.ReadOnly = true;
rtbMessage.BorderStyle = BorderStyle.None;
Form RichMessageBox = new Form();
RichMessageBox.Text = title;
RichMessageBox.StartPosition = FormStartPosition.CenterScreen;
RichMessageBox.Controls.Add(rtbMessage);
RichMessageBox.ShowDialog();
}