簡體   English   中英

如何在 PowerShell 中逐行使用 C# 從 URI 讀取文件?

[英]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()

所以我研究了不同的方法來解決我自己的問題並在此過程中學習:

1.使用[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')

2.使用[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')

3.使用[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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM