[英]How to use read file from URI using C# in PowerShell line by line?
我正在尝试将一些 C# 代码合并到我的 PowerShell 中,因为我仍在学习 C# 并在学习新语言方面站稳脚跟。
我可以在我的计算机上本地打开一个文件并逐行读取它。 但似乎无法解决如何从互联网打开文件并逐行解析它。
这可以逐行读取文件,并允许我对循环中的行项目采取行动。
$f = 'C:\tmp\tinyUF.txt'
$reader = [System.IO.File]::OpenText($f)
while (-not($reader.EndOfStream)) {
$line = $reader.ReadLine()
}
$x.Close()
这不起作用,所以我做了一些研究,发现[System.IO.File]
无法读取$f
作为提要。
$f = (Invoke-WebRequest -Uri https://algs4.cs.princeton.edu/15uf/tinyUF.txt).Content
$reader = [System.IO.File]::OpenText($f)
while (-not($reader.EndOfStream)) {
$line = $reader.ReadLine()
}
$x.Close()
所以我研究了不同的方法来解决我自己的问题并在此过程中学习:
[System.Net.WebRequest]
创建了一个$reader
object 并将其指向 URL。 但我看不到允许我读取数据的方法。 我希望它会像Invoke-WebRequest -Uri 'https://algs4.cs.princeton.edu/15uf/tinyUF.txt').Content
那样工作,我将能够解析数据,但这不起作用出去。
$reader = [System.Net.WebRequest]::Create('https://algs4.cs.princeton.edu/15uf/tinyUF.txt')
[System.Net.WebRequest]
创建了一个$reader
object 并将其指向 URL。 但我看不到允许我读取数据的方法。 我希望它会像Invoke-WebRequest -Uri 'https://algs4.cs.princeton.edu/15uf/tinyUF.txt').Content
那样工作,我将能够解析数据,但这不起作用出去。
$reader = [System.Net.WebRequest]::Create('https://algs4.cs.princeton.edu/15uf/tinyUF.txt')
[System.Net.WebClient]
我想也许我可以创建一个 WebClient 并将其指向 URI,如下所示
所以我把它放在一起,并在第二行得到错误:
$reader = [System.Net.WebClient]::new('https://algs4.cs.princeton.edu/15uf/tinyUF.txt')
MethodException: Cannot find an overload for "new" and the argument count: "1".
我尝试了那里列出的其他一些解决方案,但不太了解它们。
实际上,我找到了一个可行的解决方案。
在发布这个问题之前,我正在重新阅读和测试,我想出了一个解决我自己困境的方法。 如果其他人有兴趣,这里是解决方案:
# Set $f to point to the target file on the web
$f = 'https://algs4.cs.princeton.edu/15uf/tinyUF.txt'
# $wc to represent the WebClient
$wc = [System.Net.WebClient]::new()
# Create a stream object, using the .OpenRead method on $f
$stream = $wc.OpenRead($f)
# Create a reader of the stream using System.IO.StreamReader
$reader = [System.IO.StreamReader]($stream)
# ForEach-Object didn't play nice, so using while until it displays the last line of the file
while (-not($reader.EndOfStream)) {
$line = $reader.ReadLine();
$line
}
# Close the StreamReader
$reader.Close()
# Dispose of the WebClient
$wc.Dispose()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.