FileStream 创建文件
时间: 2024-05-16 17:17:27 浏览: 20
可以使用 C# 中的 FileStream 类来创建文件。以下是创建文件的示例代码:
```csharp
using System;
using System.IO;
class Program {
static void Main(string[] args) {
string fileName = "example.txt";
string fileContent = "This is an example file.";
// 创建新文件,如果文件已存在则覆盖
using (FileStream fs = new FileStream(fileName, FileMode.Create)) {
// 将字符串转换为字节数组
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(fileContent);
// 将字节数组写入文件
fs.Write(bytes, 0, bytes.Length);
}
}
}
```
在上面的例子中,我们使用 `FileStream` 类创建了一个名为 `example.txt` 的新文件,并将字符串 `This is an example file.` 写入文件中。如果文件已经存在,则覆盖原有的文件内容。
相关问题
filestream保存文件
好的,您想了解如何使用C++中的fstream来保存文件吗?如果是的话,可以参考以下代码示例:
```cpp
#include <fstream>
using namespace std;
int main() {
// 打开文件
ofstream outfile;
outfile.open("example.txt");
// 写入数据
outfile << "Hello, world!" << endl;
// 关闭文件
outfile.close();
return 0;
}
```
在上面的示例中,我们使用了ofstream类来创建并打开一个名为"example.txt"的文件。然后,我们使用流插入运算符(<<)将数据写入文件中。最后,我们使用close()函数关闭文件。
当然,如果您需要读取文件中的数据,您可以使用ifstream类来打开文件并读取数据。
C# FileStream如何清空文件
可以使用 `FileStream` 类的 `SetLength` 方法来清空一个文件。具体步骤如下:
1. 创建一个 `FileStream` 对象并打开文件。
```csharp
FileStream fileStream = new FileStream("filePath", FileMode.OpenOrCreate);
```
2. 调用 `SetLength` 方法,将文件长度设置为 0。
```csharp
fileStream.SetLength(0);
```
3. 关闭文件流。
```csharp
fileStream.Close();
```
完整示例代码如下:
```csharp
using System.IO;
class Program
{
static void Main(string[] args)
{
// 创建一个 FileStream 对象并打开文件
FileStream fileStream = new FileStream("filePath", FileMode.OpenOrCreate);
// 将文件长度设置为 0
fileStream.SetLength(0);
// 关闭文件流
fileStream.Close();
}
}
```
注意:该方法会完全清空文件内容,慎重使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)