// Browses file with OpenFileDialog control
private void btnFileOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialogCSV = new OpenFileDialog();
openFileDialogCSV.InitialDirectory = Application.ExecutablePath.ToString();
openFileDialogCSV.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
openFileDialogCSV.FilterIndex = 1;
openFileDialogCSV.RestoreDirectory = true;
if (openFileDialogCSV.ShowDialog() == DialogResult.OK)
{
this.txtFileToImport.Text = openFileDialogCSV.FileName.ToString();
}
}
在上面的代码中,我浏览了要打开的文件。我想要做的是,浏览文件,选择它,然后按确定。单击确定后,我想复制选择的文件,并为该重复文件提供.txt扩展名。我需要帮助才能实现这一目标。
由于
答案 0 :(得分:8)
if (openFileDialogCSV.ShowDialog() == DialogResult.OK)
{
var fileName = openFileDialogCSV.FileName;
System.IO.File.Copy( fileName ,Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName)+".txt"));
}
上面的代码会将所选文件复制为具有相同名称的txt并放入同一目录中。
如果需要覆盖具有相同名称的现有文件,请将另一个参数添加到Copy方法为true。
答案 1 :(得分:1)
您使用 File.Copy ,如下所示,
File.Copy(openFileDialogCSV.FileName., openFileDialogCSV.FileName + ".txt");
答案 2 :(得分:0)
试试这个
private void btnFileOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialogCSV = new OpenFileDialog();
openFileDialogCSV.InitialDirectory = Application.ExecutablePath.ToString();
openFileDialogCSV.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
openFileDialogCSV.FilterIndex = 1;
openFileDialogCSV.RestoreDirectory = true;
if (openFileDialogCSV.ShowDialog() == DialogResult.OK)
{
this.txtFileToImport.Text = openFileDialogCSV.FileName.ToString();
System.IO.File.Copy(this.txtFileToImport.Text,"C://123.txt")
}
}
123可以通过您想要的任何文件名进行更改。