tags:

views:

778

answers:

7

I'm working with a library that uses Environment.NewLine as it's newline char when writing a file. I need it to write Unix formatted files, and as such would like to change the newline char.

Can I change the value of Environment.NewLine?

Any other ideas (aside from converting the file post creation)?

+8  A: 

Can I change the value of Environment.NewLine?

No. If you know which platform to write for, create classes for each of these platforms and let them have their own implementation. In the simplest case, this would look as follows:

public abstract class Platform { public abstract string Newline { get; } }

public sealed class Unix : Platform {
    public override string Newline { get { return "\n"; } }
}

etc., and then just use an instance of the appropriate class.

Konrad Rudolph
That's what I figured. I'll do a conversion post file creation since it's not my library to change. Thanks!
TheSoftwareJedi
+2  A: 

According to MSDN the Environment class is sealed so therefore you wouldn't be able to inherit from it to change the value. To my knowledge that is the only way you would have been able to. Alternatively you could try and create a partial class extending the Environment class. I've never tried the latter so not sure if it will work.

Diago
A: 

The Environment.NewLine property constant, so there is no changing it. The best thing I could recommend is to change everywhere where this is used, to your own constant.

Mike_G
A: 

Does the 3rd party library write to a Stream or do you pass it the filename?

In the former case you could pass a MemoryStream and then do a replace on the newlines to get the ones you want. In the latter get it to write to a temporary file, then stream to the real file (while replacing line endings).

Richard
+1  A: 

Environment.Newline is returning the newline character of the runtime environment hosting the .Net runtime. You should not use this for conversion of newline to another platform's newline character.

I would recommend to implement your own class for conversions.

Kb
A: 

God bless you can't... you'd completely change the whole meaning of the System.Environment namespace.

What you want to do is writing something for a specific OS (no matter which environment you are running the application on), so Environment. is not what you should be using for a start.

Jcl
A: 

We had this problem where we had to change the value of NewLine to <br /> for web output.

It necessitated making another property for use in our class. There's really no way around it.

Broam