文件IO,这是Powershell中的错误吗? [英] file IO, is this a bug in Powershell?

查看:117
本文介绍了文件IO,这是Powershell中的错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Powershell中有以下代码

I have the following code in Powershell

$filePath = "C:\my\programming\Powershell\output.test.txt"

try
{
    $wStream = new-object IO.FileStream $filePath, [System.IO.FileMode]::Append, [IO.FileAccess]::Write, [IO.FileShare]::Read

    $sWriter = New-Object  System.IO.StreamWriter $wStream

    $sWriter.writeLine("test")
 }

我不断收到错误消息:

无法将参数"1"的值转换为"[IO.FileMode] :: Append" "FileStream"键入"System.IO.FileMode":无法转换值 由于无效,"[IO.FileMode] :: Append"键入"System.IO.FileMode" 枚举值.指定以下枚举值之一 然后再试一次.可能的枚举值为"CreateNew,Create, 打开,OpenOrCreate,截断,追加"."

Cannot convert argument "1", with value: "[IO.FileMode]::Append", for "FileStream" to type "System.IO.FileMode": "Cannot convert value "[IO.FileMode]::Append" to type "System.IO.FileMode" due to invalid enumeration values. Specify one of the following enumeration values and try again. The possible enumeration values are "CreateNew, Create, Open, OpenOrCreate, Truncate, Append"."

我尝试了C#中的等效功能,

I tried the equivalent in C#,

    FileStream fStream = null;
    StreamWriter stWriter = null;

    try
    {
        fStream = new FileStream(@"C:\my\programming\Powershell\output.txt", FileMode.Append, FileAccess.Write, FileShare.Read);
        stWriter = new StreamWriter(fStream);
        stWriter.WriteLine("hahha");
    }

工作正常!

我的Powershell脚本出了什么问题?顺便说一句,我正在Powershell上运行

What's wrong with my powershell script? BTW I am running on powershell

Major  Minor  Build  Revision
-----  -----  -----  --------
3      2      0      2237

推荐答案

另一种方法是仅使用值的名称,然后让PowerShell将其强制转换为目标类型:

Another way would be to use just the name of the value and let PowerShell cast it to the target type:

New-Object IO.FileStream $filePath ,'Append','Write','Read'

这篇关于文件IO,这是Powershell中的错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆