指定一个目录,写一个文本c#
时间: 2023-08-02 07:14:08 浏览: 61
以下是一个示例代码,用于在指定目录下创建一个名为 "example.txt" 的文本文件,并向其中写入一些文本内容:
```csharp
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string directoryPath = @"C:\example\";
string fileName = "example.txt";
string fileContent = "This is an example text.";
// Combine directory path and file name to get the full file path
string filePath = Path.Combine(directoryPath, fileName);
// Create the directory if it doesn't exist
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
// Write the text content to the file
File.WriteAllText(filePath, fileContent);
Console.WriteLine("File created and text written!");
}
}
```
请注意,此代码假定您具有足够的权限在指定的目录中创建文件。如果您没有权限,则可能需要使用管理员权限或联系系统管理员。