Answer to Question #57860 in C# for ahmad

Question #57860
write a program in c# that allows the user to open file Test.text located at "E:/OfficeDocuments/Test.text" the user input string which should be copied to the file
1
Expert's answer
2016-02-18T07:45:09-0500
using System;
using System.IO;

namespace stringCopy
{
class Program
{
private static void CreateIfNotExist(string pathToFile)
{
if (File.Exists(pathToFile))
{
return;
}

File.CreateText(pathToFile).Close();
}

private static void DisplayFileContent(string pathToFile)
{
string content = File.ReadAllText(pathToFile);
Console.WriteLine(content);
}

private static void AppendToFile(string pathToFile, string content)
{
// End of string in the end of file
File.AppendAllText(pathToFile, content + Environment.NewLine);
}

private static void Main()
{
const string pathToFile = @"E:/OfficeDocuments/Test.text";

try
{
CreateIfNotExist(pathToFile);

Console.WriteLine("Initial file content:");
DisplayFileContent(pathToFile);

Console.WriteLine("Enter string:");
string content = Console.ReadLine();

AppendToFile(pathToFile, content);

Console.WriteLine("Modified content:");
DisplayFileContent(pathToFile);
}
catch (Exception exception)
{
Console.WriteLine("An error occured: " + exception.Message);
}
}
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS