我正在創建一個應用程序,允許我打開.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());
}
}
它說,它是打開文件對話框正在使用中它無法達到它!任何建議或建議將非常感激!
你有一堆沒有理由存在的變量。 – SLaks
在'WriteToTextFile()'函數中,'openFileDialog1'從哪裏來?它是一個全局變量嗎?這是所有相關的代碼嗎? –
@JayBuckman是的,我試圖讓它成爲一個全局變量(我知道,不是一個好的舉動),只是爲了測試並看看我是否可以將其作爲一個靜態路徑並在稍後參考。不幸的是,這不起作用。我沒有包含的唯一代碼是BindGrid方法,它只是將我的paramList設置爲我的數據源。 – Tarheel81