-2

Good day,

I'm trying to create a file programmatically using C# and that file will be attach or send to email.

I want to file contains a string just like below..

var stringInsideTheFile = new StringBuilder("Hello, I'm a test only");

I'm trying, File but requires a path. which is I don't need.

var test = File.WriteAllLines(path, content);

To summarize, I just want a help how to create a file programmatically and use that object with a content from string builder.

any help?

AppleCiderYummy
  • 369
  • 1
  • 7
  • 20
  • 1
    Possible duplicate of [Create and write to a text file inmemory and convert to byte array in one go](https://stackoverflow.com/questions/36661211/create-and-write-to-a-text-file-inmemory-and-convert-to-byte-array-in-one-go) – Ryan Wilson Mar 29 '19 at 15:04
  • It seems like `MemoryStream` is the answer you're looking for. – Vulpex Mar 29 '19 at 15:06
  • 2
    Something isn't a "file" until it's written to a file system, which involves a path. How are you "attaching" the data to your email? Is there perhaps an overload of one of those methods which accepts a `Stream`? – David Mar 29 '19 at 15:07
  • you can store the file on the server and then send that in the attachment – Hitesh Anshani Mar 29 '19 at 15:21

1 Answers1

0

You could simply store the file in the temp directory.

var stringInsideTheFile = "Hello, I'm a test only";
var filename = string.Format("%TEMP%\{0}", DateTime.UtcNow.Ticks);
var test = File.WriteAllText(filename, stringInsideTheFile);
MailMessage message = new MailMessage();
message.Attachments.Add(new Attachment(filename));
File.Delete(filename);
Bart van der Drift
  • 1,287
  • 12
  • 30