我想要做的事情很可能非常简单,但是花了几个小时我仍然无法弄清楚如何正确地做到这一点。我可以使用openfiledialog打开一个文本文件,但无法想出保存回同一个文件。我还希望能够在写入之前检查文件是否正在使用。这是我打开和保存按钮的代码:
public void openToolStripMenuItem_Click(object sender, EventArgs e)
{
//This if statement checks if the user has saved any changes to the list boxes
if (MessageBox.Show(
"Have you saved your work?\nOpening a new file will clear out all list boxes.",
"Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
//Clears out the listboxes
this.itemListBox.Items.Clear();
this.priceListBox.Items.Clear();
this.qtyListBox.Items.Clear();
//This will open the file dialog windows to allow the user to chose a file
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Harv's Hardware";
fileDialog.InitialDirectory = Directory.GetCurrentDirectory();
//File Filter
fileDialog.Filter = "txt files (*.txt)|*.txt";
fileDialog.FilterIndex = 2;
fileDialog.RestoreDirectory = true;
//This if statement executes is the user hits OK
if (fileDialog.ShowDialog() == DialogResult.OK)
{
//StreamReader readFile = File.OpenText(fileDialog.FileName);
currentFile = new StreamWriter(OpenFileDialog.FileName);
String inputString = null;
while ((inputString = readFile.ReadLine()) != null)
{
this.itemListBox.Items.Add(inputString);
inputString = readFile.ReadLine();
this.priceListBox.Items.Add(inputString);
inputString = readFile.ReadLine();
this.qtyListBox.Items.Add(inputString);
}
}
}
}
并保存按钮
//关闭并打开文件
//Creates a new saveDialog
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.ShowDialog();
//Listens to the user input
StreamWriter writeFile = File.CreateText(saveDialog.FileName);
int indexInteger = 0;
//Writes the actual File
while (indexInteger < priceListBox.Items.Count)
{
writeFile.WriteLine(itemListBox.Text);
writeFile.WriteLine(itemListBox.Text);
writeFile.WriteLine(qtyListBox.Text);
indexInteger++;
}
}
感谢您的帮助!
答案 0 :(得分:1)
使用SaveFileDialog而不是OpenFileDialog,可以使用FileStream写入文件。
要检查文件是否正在使用,这就是我的工作..
public bool IsFileInUse(String file)
{
bool retVal = false;
try
{
using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
//file is not locked
}
}
catch
{
retVal = true;
}
return retVal;
}