I have a question about an issue I am having on my final project. Within my ItemEntry.cs form, I am trying to get the application to append the already existing .txt file, rather than prompt the user to replace it. I can't seem to get the StreamWriter and FileStream to allow the user to write to the file.
Any help would be appreciated.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace InventoryApplication
{
public partial class ItemEntry : Form
{
private StreamWriter fileWriter;
private FileStream output;
private FileStream input;
private StreamReader fileReader;
public ItemEntry()
{
InitializeComponent();
}
private void ItemEntry_Load(object sender, EventArgs e)
{
}
private void SaveButton_Click(object sender, EventArgs e)
{
SaveFileDialog fileChooser = new SaveFileDialog();
DialogResult result = fileChooser.ShowDialog();
string fileName;
fileChooser.CheckFileExists = false;
if (result == DialogResult.Cancel)
return;
fileName = fileChooser.FileName;
if (fileName == "" || fileName == null)
MessageBox.Show("Invalid File Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
try
{
output = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
fileWriter = new StreamWriter(output);
}
catch (IOException)
{
MessageBox.Show("Error opening file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
enterButton.Enabled = true;
SaveButton.Enabled = false;
}
private void ExitButton_Click(object sender, EventArgs e)
{
fileWriter.Close();
output.Close();
this.Close();
}
private void enterButton_Click(object sender, EventArgs e)
{
Product product;
int itemnum;
string department;
string supplier;
float price;
string description;
itemnum = int.Parse(textBox1.Text);
department = comboBox1.SelectedItem.ToString();
supplier = textBox3.Text;
price = float.Parse(textBox4.Text);
description = textBox5.Text;
product = new Product(itemnum, department, supplier, price, description);
fileWriter.WriteLine(product.ItemNum + ", " + product.Department + ", " + product.Supplier + ", " + product.Price + ", " + product.Description);
}
private void openButton_Click(object sender, EventArgs e)
{
SaveFileDialog fileChooser = new SaveFileDialog();
DialogResult result = fileChooser.ShowDialog();
string fileName;
fileChooser.CheckFileExists = false;
if (result == DialogResult.Cancel)
return;
fileName = fileChooser.FileName;
if (fileName == "" || fileName == null)
MessageBox.Show("Invalid File Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
try
{
output = new FileStream(fileName, FileMode.Append);
fileWriter = new StreamWriter(output, true);//always asking to overwrite file. how to open existing file for appending?
}
catch (IOException)
{
MessageBox.Show("Error opening file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
enterButton.Enabled = true;
}
}
}