1

I have this java code, that I want to translate to c#:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.printf("\n\n+++++ %s %s\n",Environment.UserName, new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aa").format(new Date()));
0

3 Answers 3

5

Something like:

  // You can use "using" blocks guarantee streams are disposed (like try/finally { boas.Close(); })
  using (var baos = new MemoryStream())
  {
    // Stream encodes as UTF-8 by default; specify other encodings in this constructor
    using (var ps = new StreamWriter(baos))
    {
      // Format string almost the same, but 'tt' for 'am/pm'
      // Could also use move formatting into
      //    DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss tt")
      // or ToLongDateString and ToLongTimeString for locale-defined formats
      ps.Write("\n\n+++++ {0} {1:MM/dd/yyyy HH:mm:ss tt}\n", Environment.UserName, DateTime.Now);

      // Need to close or flush the StreamWriter stream before the bytes will
      // appear in the MemoryStream
      ps.Close();
    }

    // Extract bytes from MemoryStream
    var bytes = baos.ToArray();
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't the ps.Close() redundant in this case as the using clause will do this anyway?
@Druzil I generally prefer to explicitly close them myself anyway to avoid making assumptions about Dispose. But you're almost certainly right.
3
 string strVal = String.Format("\n\n+++++ {0} {1}\n", System.Environment.UserName, String.Format(
"{0:MM/dd/yyyy}", DateTime.Now));

Console.Write(strVal);

Comments

3
MemoryStream mem = new MemoryStream();
StreamWriter writer = new StreamWriter(mem);

writer.WriteLine(String.Format("\n\n+++++ {0} {1}\n",Environment.UserName,DateTime.Now.ToString()));

Or something similar...

Comments

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.