File.Create 方法 (System.IO)

您所在的位置:网站首页 路径或文件名无效 File.Create 方法 (System.IO)

File.Create 方法 (System.IO)

2023-12-16 11:39| 来源: 网络整理| 查看: 265

在指定路径中创建、截断和覆盖文件。

public: static System::IO::FileStream ^ Create(System::String ^ path); public static System.IO.FileStream Create (string path); static member Create : string -> System.IO.FileStream Public Shared Function Create (path As String) As FileStream 参数 path String

要创建的文件的路径及名称。

返回 FileStream

一个 FileStream,它提供对 path 中指定的文件的读/写访问。

例外 UnauthorizedAccessException

调用方没有所要求的权限。

- 或 -

path 指定了一个只读文件。

- 或 -

path 指定了一个隐藏文件。

ArgumentException

.NET Framework 和 2.1 之前的 .NET Core 版本:path是一个零长度字符串,仅包含空格,或者包含一个或多个无效字符。 你可以使用 GetInvalidPathChars() 方法查询无效字符。

ArgumentNullException

path 为 null。

PathTooLongException

指定的路径和/或文件名超过了系统定义的最大长度。

DirectoryNotFoundException

指定的路径无效(例如,它位于未映射的驱动器上)。

IOException

创建文件时发生 I/O 错误。

NotSupportedException

path 的格式无效。

示例

以下示例在指定路径中创建一个文件,将一些信息写入该文件,并从该文件读取。

using namespace System; using namespace System::IO; using namespace System::Text; int main() { String^ path = "c:\\temp\\MyTest.txt"; // Create the file, or overwrite if the file exists. FileStream^ fs = File::Create( path ); try { array^info = (gcnew UTF8Encoding( true ))->GetBytes( "This is some text in the file." ); // Add some information to the file. fs->Write( info, 0, info->Length ); } finally { if ( fs ) delete (IDisposable^)fs; } // Open the stream and read it back. StreamReader^ sr = File::OpenText( path ); try { String^ s = ""; while ( s = sr->ReadLine() ) { Console::WriteLine( s ); } } finally { if ( sr ) delete (IDisposable^)sr; } } using System; using System.IO; using System.Text; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; try { // Create the file, or overwrite if the file exists. using (FileStream fs = File.Create(path)) { byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file."); // Add some information to the file. fs.Write(info, 0, info.Length); } // Open the stream and read it back. using (StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } open System.IO open System.Text let path = @"c:\temp\MyTest.txt" // Create the file, or overwrite if the file exists. do use fs = File.Create path let info = UTF8Encoding(true) .GetBytes "This is some text in the file." // Add some information to the file. fs.Write(info, 0, info.Length) // Open the stream and read it back. do use sr = File.OpenText path let mutable s = sr.ReadLine() while isNull s |> not do printfn $"{s}" s


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3