【发布时间】:2017-06-28 17:39:16
【问题描述】:
我正在创建一个应用程序,它允许我打开一个 .txt 文件并在 DataGridView 中编辑值(重量 = 60、高度 = 50 等)。我的问题是我可以使用 OpenFileDialog 上传 .txt 文件,但无法重写并将其保存在之前的位置。
为了澄清,这是我上传文本文件的方法:
private void btnUpload_Click(object sender, EventArgs e)
{
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "C:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var compareType = StringComparison.InvariantCultureIgnoreCase;
var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
var extension = Path.GetExtension(openFileDialog1.FileName);
if (extension.Equals(".txt", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(openFileDialog1.FileName);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split('=');
paramList.Add(new Parameter(words[0], words[1]));
}
BindGrid();
}
}
以及我尝试保存文件的内容:
public void WriteToTextFile(DataGridView dgvParam)
{
String file_name = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
using (StreamWriter objWriter = new StreamWriter(openFileDialog1.FileName))
{
for (Int32 row = 0; row < dgvParam.Rows.Count - 1; row++)
{
StringBuilder sb = new StringBuilder();
for (Int32 col = 0; col < dgvParam.Rows[row].Cells.Count; col++)
{
if (!String.IsNullOrEmpty(sb.ToString()))
sb.Append("="); //any delimiter you choose
sb.Append(dgvParam.Rows[row].Cells[col].Value.ToString().ToUpper());
}
objWriter.WriteLine(sb.ToString());
}
}
它说它是 openFileDialog 当前正在使用中,但无法访问它!任何建议或建议将不胜感激!
【问题讨论】:
-
你有一堆没有理由存在的变量。
-
WriteToTextFile()函数中,openFileDialog1来自哪里?是全局变量吗?这是所有相关代码吗? -
@JayBuckman 是的,我试图将其设为全局变量(我知道,这不是一个好的举措),只是为了测试并查看是否可以将其设为静态路径并稍后引用它。不幸的是,这没有奏效。我没有包含的唯一代码是 BindGrid 方法,它只是将我的 paramList 设置为我的数据源。
-
代码中有一些重复。
using (myStream = openFileDialog1.OpenFile())实际上将文件内容读入myStream,但您从不使用它。相反,您使用StreamReader reader = new StreamReader(openFileDialog1.FileName);打开一个新阅读器。但是您永远不会像@slaks 提到的那样处置让文件保持打开状态的阅读器。
标签: c# datagridview openfiledialog savefiledialog