我有一个按钮,一旦点击就会使用stremReader来读取文本文件,还有一个文件夹浏览器对话框来保存文件。保存文件并再次单击该按钮后,我收到错误消息,说它无法找到文本文件,并尝试从保存上一个文档的路径中读取文本文件。
有什么方法可以解决这个问题吗?
以下是代码的一部分:
private void Invoice_Load(object sender, EventArgs e)
{
try
{
StreamReader sr = new StreamReader(@"../../DatabasePath");
dataBase = sr.ReadLine();
if (dataBase == null)
{
MessageBox.Show("Please use this to choose the location of the database.");
Process.Start(@"..\..\DatabaseChooser.exe");
ready = false;
}
if (!ready)
{
while (IsProcessOpen("DatabaseChooser"))
{
ready = false;
}
ready = true;
if (ready)
{
doIfReady();
}
}
else if (ready)
{
doIfReady();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnCreateInvoice_Click(object sender, EventArgs e)
{
int SelectColumnIndex = 5;
foreach (DataGridViewRow row in dataGridViewInvoice.Rows)
{
if (row.Cells[SelectColumnIndex].Value != null &&
Convert.ToBoolean(row.Cells[SelectColumnIndex].Value) == true)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.OwningColumn.Index != SelectColumnIndex)
{
data += (cell.Value + " "); // do some thing
}
}
data += System.Environment.NewLine;
total += (int)row.Cells["TotPrice"].Value;
}
}
MessageBox.Show("Please choose your invoice template", "Template");
OpenFileDialog op = new OpenFileDialog();
op.ShowHelp = true;
op.Filter = "Microsoft Word Documents 97-2003 (*.doc)|*.doc|Microsoft Word 2007 (*.docx)|*.docx";
if (op.ShowDialog() == DialogResult.Cancel)
{
this.Hide();
}
MessageBox.Show("Please choose where you want to save the invoice", "Save");
FolderBrowserDialog fd = new FolderBrowserDialog();
fd.Description = "Please choose";
if (fd.ShowDialog() == DialogResult.Cancel)
{
this.Hide();
}
string path = fd.SelectedPath + "\\" + txtFileName.Text + ".doc";
CreateWordDoc(op.FileName, path);
}
答案 0 :(得分:0)
首先,您可能想要发布一些代码。其次,您应该使用SaveFileDialog来保存文件而不是FolderBrowser。
答案 1 :(得分:0)
我认为你应该改变这部分
StreamReader sr = new StreamReader(@"../../DatabasePath");
使用绝对路径 例如:
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
这里dir是主要的执行目录 当您使用OpenDialog时,可能会更改当前路径,因此您无法再使用 ../../ 找到路径。
另一件事:当您使用Process.Start(@"..\..\DatabaseChooser.exe");
时,等待您的流程完成:如果您创建Process ps
并使用ps.WaitForExit()
,我认为您可以做得更好。
答案 2 :(得分:0)
我假设你遇到了麻烦:
StreamReader sr = new StreamReader(@"../../DatabasePath");
将其更改为:
File f = new File(@"../../DatabasePath");
然后执行f.GetAbsolutePath以找出它实际获取文件的位置。
还有一些评论:
if (op.ShowDialog() == DialogResult.Cancel)
{
this.Hide();
}
如果用户点击取消,代码仍将尝试运行。并尝试CreateWordDoc。