1

Need your help to remove Carriage return (`r) & new line character (`n) from my XML file. I'm getting System.OutOfMemoryException error

The size of File :600 MB

Number of Lines: 1

Input File Format

<File1>
 <SubFile1> </SubFile1>
 <SubFile2> </SubFile2>
 <SubFile3> </SubFile3>
 .........
 <SubFilen> </SubFilen>
</File1>

Code used

$content = [IO.File]::ReadAllText($input_File)
$content = $content.Replace("`r","")
$content = $content.Replace("`n","")
[system.io.file]::WriteAllText($Output_File,$content)

Also tried

Get-Content 

I tried with MaxMemoryPerShellMB 1024, 2048, 4096 but no luck.

2
  • (Get-Content .\file.xml)-join'' Commented May 16, 2016 at 8:12
  • I'm not getting any error if I execute it from Powershell prompt. C:\Temp\File_Encoding.ps1 "input.xml" "output.xml" I'm getting error when I try to execute like below C:\Windows\syswow64\Windowspowershell\v1.0\Powershell.exe -noprofile -executionpolicy bypass -File "C:\Temp\Change_File_Encoding.ps1" "input.xml" "output.xml" Commented May 17, 2016 at 5:44

1 Answer 1

1

There is a nice article from Don Jones Why Get-Content Ain’t Yer Friend.

Try to use a StreamReader to read the file line by line and use a StreamWriterto write a new (temp) file line by line. After you are finish, just replace the files:

$streamReader = New-Object System.IO.StreamReader -Arg "yourFile.xml"
$streamWriter = [System.IO.StreamWriter] "tmp.xml"

while ($line = $streamReader.ReadLine()) {
  $replacedLine = $line -replace '`r|`n'
  $streamWriter.Write($replacedLine);
}

$streamReader.close()
$streamWriter.close()

Remove-Item "yourFile.xml" -Force
Rename-Item "tmp.xml" "yourFile.xml"
Sign up to request clarification or add additional context in comments.

3 Comments

WriteLine() introduces another newline, defeating the purpose
Of course, thanks for the hint. He have to use Write instead - fixed my answer.
Still I'm getting the same error. ERROR encountered - Control has passed to Catch Block Exception of type 'System.OutOfMemoryException' was thrown. Error occurred at line 56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.