windows 如何在Windows7操作系统中使用C#在c盘创建文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4395162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create a file in c drive using C# in Windows7 OS
提问by Sreekumar P
how to create a file in c drive using C# in Windows7 OS
如何在Windows7操作系统中使用C#在c盘创建文件
回答by Cody Gray
The following sample code will create a folder and a subfolder on your C: drive, and then create a new file in the subfolder with a random file name. Finally, some data will be written to the file. (The code is well-commented, and you should be able to figure out what's going on by studying it carefully.)
以下示例代码将在您的 C: 驱动器上创建一个文件夹和一个子文件夹,然后在该子文件夹中创建一个具有随机文件名的新文件。最后,一些数据将写入文件。(代码有很好的注释,你应该能够通过仔细研究来弄清楚发生了什么。)
public class CreateFileOrFolder
{
static void Main()
{
// Specify a "currently active folder"
string activeDir = @"c:\testdir2";
//Create a new subfolder under the current active folder
string newPath = System.IO.Path.Combine(activeDir, "mySubDir");
// Create the subfolder
System.IO.Directory.CreateDirectory(newPath);
// Create a new file name. This example generates a random string.
string newFileName = System.IO.Path.GetRandomFileName();
// Combine the new file name with the path
newPath = System.IO.Path.Combine(newPath, newFileName);
// Create the file and write to it.
// DANGER: System.IO.File.Create will overwrite the file
// if it already exists. This can occur even with random file names.
if (!System.IO.File.Exists(newPath))
{
using (System.IO.FileStream fs = System.IO.File.Create(newPath))
{
for (byte i = 0; i < 100; i++)
{
fs.WriteByte(i);
}
}
}
// Read data back from the file to prove that the previous code worked.
try
{
byte[] readBuffer = System.IO.File.ReadAllBytes(newPath);
foreach (byte b in readBuffer)
{
Console.WriteLine(b);
}
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
See all the gory details by reading the original MSDN How-To article.
通过阅读原始 MSDN How-To 文章查看所有血腥细节。