60 314
Assignments Done
98,1%
Successfully Done
In April 2018

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
Expert's answer
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 first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions