C# application.exe不在Win10工作,但它在我的Win7上工作。我尝试在Win10中进行调试,它显示了这个错误,在win7中是正确的。
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string fullComputerName = Environment.MachineName;
//Create a Folder Path
string createFolderPath = @"C:\\Users\\" +fullComputerName+"\\Documents\\Cheques";
//Create a File Inside of a Folder
string createTxtFile= createFolderPath + "\\ChequeForDeposit.TXT";
try
{
if(!Directory.Exists(createFolderPath))
{ return; }
Directory.CreateDirectory(createFolderPath);
}
catch { }
finally { }
if(!File.Exists(createTxtFile))
{ File.Create(createTxtFile); }//The error is here
}
}
}
当我签入我的win7 pc时,它会创建一个文件夹和一个文本文件。但不是在Win10。太奇怪了。
发布于 2016-11-05 20:56:16
try/catch不能确保目录文件夹的存在(在尝试创建文件夹时可能会生成异常)。因此,在创建文件之前,请立即检查文件夹是否存在。你的情况不对。如果文件夹不存在,则应返回,否则创建。
try
{
if(Directory.Exists(createFolderPath) && !File.Exists(createTxtFile))
{
File.Create(createTxtFile);
}
}
还要检查许可问题。检查桌面文件夹的权限。在Windows中,右键单击桌面文件夹,选择“属性”,然后转到“安全”选项卡。您应该拥有该文件夹的写权限。
发布于 2016-11-05 21:41:59
我认为文件夹C:\Users\是保护的系统文件夹。要么以管理员的身份运行,要么以的身份在其他驱动器中创建文件,例如:
@"D:\Users\" +fullComputerName+"\Documents\Cheques"
https://stackoverflow.com/questions/40446108
复制相似问题