gpt4 book ai didi

c# - FileMode.CreateNew 或 File.Create 没有创建任何东西,也没有错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:43:57 27 4
gpt4 key购买 nike

我有这个简单的基本代码来创建新文件并向其中写入一些数据。问题是当我运行程序时,我没有得到任何东西,既没有创建文件,也没有显示任何错误消息或异常,即使在调试代码时也没有出现错误。

这是代码:

namespace WriteToFile
{
class WriteData
{
static void Main(string[] args)
{
string nFile = @"C:\Users\Ashraf\Documents\newFilex.txt";
FileStream fs = null;

// checking if file already exists and getting user input on deleting it or not
if (File.Exists(nFile))
{
Console.WriteLine("File already exists!");
Console.WriteLine("What would you like to do? \n");
Console.WriteLine("\"DELETE\" to delete the file, or press Enter to continue ?");
string ans;
ans = Console.ReadLine();
switch (ans)
{
case "":
Console.WriteLine("continue ...");
break;
case "DELETE":
File.Delete(nFile);
if (File.Exists(nFile))
{
Console.WriteLine("Error deleting file!");
}
else
{
Console.WriteLine("File deleted successfuly");
}
break;
default:
break;
}


// continue creating new file and inserting data to it
try
{
fs = new FileStream(nFile, FileMode.CreateNew, FileAccess.ReadWrite);
for (char c = 'A'; c <= 'Z'; c++)
{
fs.WriteByte((byte)c);
}
Console.WriteLine("File created and data written to file successfuly");
}
catch (IOException ce)
{
Console.WriteLine("\t File couldn't be created! \t \n" + ce.Message);
}
finally
{
Console.Read();
fs.Dispose();
}
}
}
}
}

最佳答案

你的缩进错了:.试试这个,使用 if(exists)try { Create 在同一层:

if (File.Exists(nFile))
{
Console.WriteLine("File already exists!");
...
}
// continue creating new file and inserting data to it
try
{
fs = new FileStream(nFile, FileMode.CreateNew, FileAccess.ReadWrite);
...
}

关于c# - FileMode.CreateNew 或 File.Create 没有创建任何东西,也没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28087227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com