mack
mack

Reputation: 2965

C# in Powershell StreamWriter

I have a Powershell script in which I've dropped a bit of C# code. The code does a regex search of a file and if it finds a match, it writes it to a datatable that is returned to Powershell for further processing. Everything was working fine until I added a StreamWriter writeline. As soon as I do that, the script completely bombs. Here is a snippet of the code. I've marked the line that blows up the script. Any idea why this might be happening here? If I comment out that line, the script works fine.

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
                }

Upvotes: 0

Views: 1792

Answers (1)

Micah Rowland
Micah Rowland

Reputation: 11

Ran into the same problem today. StreamWriter doesn't use the current directory that powershell is in. By default, StreamWriter creates the file in the directory returned by this command:

[IO.Directory]::GetCurrentDirectory()

This will return the directory that powershell was opened to, not the directory that the script is running from. The best way to get this to work, the way I used, is to put this as the first line of the script:

[IO.Directory]::SetCurrentDirectory($pwd)

This will direct the streamwriter file output to the current working directory. You can replace $pwd with any other directory you wish, but remember, if it is a relative directory, the file will be placed in that directory relative to the directory returned by getcurrentdirectory.

PHEW!

Upvotes: 1

Related Questions