如何使用“打开文件”对话框
本文关键字:打开文件 对话框 文件 何使用 | 更新日期: 2023-09-27 18:37:22
我正在尝试编写一个代码来使用公钥加密文本并使用私钥和密码进行解密。
我不太擅长编程语言,因为我不是编程学生。但是对于我的小项目,我需要编写一些关于加密的程序。
对于下面的代码,使用我的 c 驱动器中的文本文件使用公钥进行编码。但是我想使用 openfiledialog 来选择文件而不是手动定向它(不是很实用)
如果有人可以帮助我编辑代码,非常感谢。附言我真的不知道如何将 openfiledialog 应用到我的代码中。当我使用来自YouTube和Google的信息时,我不断收到错误。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using DidiSoft.Pgp;
namespace TEST2
{
public partial class Form1 : Form
{
PGPLib pgp = new PGPLib();
public Form1()
{
InitializeComponent();
}
private void encryptButton_Click(object sender, EventArgs e)
{
string testingstring = pgp.EncryptString(testTextBox.Text, new FileInfo(@"c:'TCkeyPublic.txt"));
encryptedtextTextBox.Text = testingstring;
}
private void decryptButton_Click(object sender, EventArgs e)
{
try
{
String plainString = pgp.DecryptString(encryptedtextTextBox.Text,
new FileInfo(@"c:'TCkeyPrivate.txt"), passphraseTextBox.Text);
decryptedtextTextBox.Text = plainString;
encryptedtextTextBox.Text = "";
passphraseTextBox.Text = "";
}
catch
{
MessageBox.Show("ERROR! Please check passphrase and do not attempt to edit cipher text");
}
}
private void passphraseTextBox_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
假设您使用的是WinForms。
只需创建一个OpenFileDialog
实例,调用ShowDialog
,如果用户没有取消操作,则读取FileName
属性:它将包含所选文件的完整路径。在代码中:
var dlg = new OpenFileDialog();
if (dlg.ShowDialog() != DialogResult.OK)
return;
new FileInfo(dlg.FileName, passphraseTextBox.Text);
当然,您可能需要让用户快速过滤要显示的文件,您可以使用Filter
属性:
var dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
您甚至可以允许多项选择,将Multiselect
设置为 true
,您将在 FileNames
属性中获得所有选定的文件:
var dlg = new OpenFileDialog();
dlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
dlg.Multiselect = true;
if (dlg.ShowDialog() != DialogResult.OK)
return;
foreach (var path in dlg.FileNames)
{
new FileInfo(path, passphraseTextBox.Text);
// ...
}
private void decryptButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:''" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
String plainString = pgp.DecryptString(encryptedtextTextBox.Text,new FileInfo(openFileDialog1.FileName), passphraseTextBox.Text);
decryptedtextTextBox.Text = plainString;
encryptedtextTextBox.Text = "";
passphraseTextBox.Text = "";
}
catch
{
MessageBox.Show("ERROR! Please check passphrase and do not attempt to edit cipher text");
}
}
}