3

I'm implementing a Windows application to make planning projects easier at my workplace and I was wondering if there's any clever way of making a txt-file nicely structured.

The application is really very simple, pretty much what it does is give the user a question which is answered in a textbox bellow. The question AND the answer are then both sent to a file but it looks very tacky.

Example:

Question?Answer!Question?Answer!

I would like it to be more like this:

Question?
Answer!

Question?
Answer!

I was also curious about other types files, is it possible to use Pdf or MS word the same way as txt?

3 Answers3

3

You can use File.AppendAllLines() and pass in the different strings as an array. They will appear as separate lines in the text file. You'll also need to add a using System.IO at the top of your file.

For example:

// Ensure file exists before we write
if (!File.Exists("<YOUR_FILE_PATH>.txt"))
{
    using (File.CreateText("<YOUR_FILE_PATH>.txt")) {}
}

File.AppendAllLines("<YOUR_FILE_PATH>.txt", new string[] {
    "Question1",
    "Answer1",
    "Question2",
    "Answer2",
    "Question3",
    "Answer3"
});

I hope this is what you're after - the question is a little vague.

As for Word and PDF files, this is more complex. Here's a link to a StackOverflow question about Word:

How can a Word document be created in C#?

and one about PDF:

Creating pdf files at runtime in c#

Community
  • 1
  • 1
Dave R.
  • 7,206
  • 3
  • 30
  • 52
1

For a simple text file you could use

StringBuilder fileData = new StringBuilder();
fileData.AppendLine("Question: blah! blah! blah! blah!");
fileData.AppendLine("Answer: blah! blah! blah! blah!");

FileStream fs = new FileStream("yourFile.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.Write(fileData.ToString());
sw.Flush();
fs.Flush();
fs.Close();

But of course it won't give you that bold question flavor, for that you would have to use something else,

like MS Word interop, to learn that visit here.

yogi
  • 19,175
  • 13
  • 62
  • 92
1

I wanted to mention the String.Format function.

suppose, you have your strings question and answer, you could do some

using (var stream = new StreamWriter('myfile.txt', true)) // append=true
  stream.Write(String.Format("\n{0}\n{1}\n\n{2}\n", 
                             question, 
                             new String('=',question.Length), 
                             answer);

to get a text file like

Question 1
==========
Answer

Second Question
===============
Answer

You might also want to use String.Trim() on question to get rid of leading and trailing whitespace (question = question.Trim()), so the "underline" effect looks nicely.

MartinStettner
  • 28,719
  • 15
  • 79
  • 106