[英]C# in Powershell StreamWriter
我有一個Powershell腳本,其中放入了一些C#代碼。 該代碼對文件進行正則表達式搜索,如果找到匹配的文件,則將其寫入數據表,該數據表返回給Powershell進行進一步處理。 一切正常,直到我添加了StreamWriter編寫行。 一旦我這樣做,腳本就會完全炸毀。 這是代碼片段。 我已經標記了炸毀腳本的那一行。 知道為什么會在這里發生嗎? 如果我注釋掉那行,腳本可以正常工作。
Regex reg = new Regex(regex);
using (StreamReader r = new StreamReader(SFile))
{
string revisedfile = FileName.txt
string line;
while ((line = r.ReadLine()) != null)
{
using (StreamWriter writer = new StreamWriter(revisedfile, true))
{
// Try to match each line against the Regex.
Match m = reg.Match(line);
if (m.Success)
{
DateTime result;
if (!(DateTime.TryParse(m.Groups[0].Value, out result)))
{
// add it to the DT
MatchTable.Rows.Add(x, m.Groups[0].Value, line);
// write it to the "revised" file
writer.WriteLine(reg.Replace(line, match => DateTime.Now.ToString("MM-dd-yyyy"))); // this is the line that blows it up
}
今天遇到了同樣的問題。 StreamWriter不使用Powershell所在的當前目錄。默認情況下,StreamWriter在此命令返回的目錄中創建文件:
[IO.Directory]::GetCurrentDirectory()
這將返回打開powershell的目錄,而不是腳本運行所在的目錄。 我使用過的最好的方法是,將其作為腳本的第一行:
[IO.Directory]::SetCurrentDirectory($pwd)
這會將流寫入器文件輸出定向到當前工作目錄。 您可以將$ pwd替換為所需的任何其他目錄,但是請記住,如果它是相對目錄,則文件將相對於getcurrentdirectory返回的目錄放置在該目錄中。
EW!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.