问题描述
我在 VS 2019 中有一个 c# 脚本,现在我想将值写入文件,但是我必须将 .txt 文件放在哪里?之后我想用 Inno Setup Compiler 制作一个 Setup.exe。
所以我的问题是在我的程序编程期间以及从 Setup.exe 安装 .exe 之后,我应该把文件放在哪里才能访问它。
我听说过,但我不知道这是做什么的:
string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),"combinations.txt");
现在我在函数顶部设置了权限,因为它提到了 here 但我仍然遇到问题
[PermissionSet(SecurityAction.Demand,Name = "FullTrust")]
private void button4_Click(object sender,EventArgs e)
{
string date = DateTime.Now.ToString("g");
string exePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
string logFile = "combinations.txt";
if (File.Exists(Path.Combine(exePath,logFile)) == false)
File.Create(Path.Combine(exePath,logFile));
using (StreamWriter wr = File.AppendText(Path.Combine(exePath,logFile)))
{
wr.WriteLine(date + "|" + date);
wr.Close();
}
}
感谢您的帮助
解决方法
我认为您可以正确使用此路径 它位于您的 exe 所在的文件夹中。
例如 exe 文件夹中的写入日志文件。 在调试模式下,它在调试文件夹中。
public static void LogWrite(string mes)
{
string exepath= Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
DateTime _dt = DateTime.Now;
string logFile= "Log.Inc";
if (File.Exists(Path.Combine(exepath,logFile)) == false)
File.Create(Path.Combine(exepath,logFile));
using (StreamWriter wr = File.AppendText(Path.Combine(exepath,logFile)))
{
wr.WriteLine(_dt.ToString("dd/MM/yyyy") + "|" + _dt.ToString("hh:mm") + "|" + mes);
wr.Close();
}
}
,
根据我的测试,你可以试试下面的代码,在你发布的时候把信息记录到txt文件中。
private void button1_Click(object sender,EventArgs e)
{
string date = DateTime.Now.ToString("g");
string exePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
string logFile = "combinations.txt";
using (StreamWriter wr = new StreamWriter(Path.Combine(exePath,logFile),true))
{
wr.WriteLine(date + "|" + date);
wr.Close();
}
string path = Path.Combine(exePath,logFile);
MessageBox.Show(path);
}
如果使用上述代码,则无需检查文件是否创建。 另外,我在最终代码中显示了txt文件的路径。