public class Processor
{
public void ProcessFile(string FilePath)
{
string msg = null;
if(!DoActionWithFile(FilePath, out msg))
{
Console.WriteLine(string.Format("Ошибка: {0}", msg));
}
}
private bool DoActionWithFile(string FilePath, out string msg)
{
msg = "";
if(string.IsNullOrEmpty(FilePath))
{
msg = "Отсутствует путь к файлу.";
return false;
}
FileInfo fileInfo = new FileInfo(FilePath);
if(!fileInfo.Exists)
{
msg = "Файл с заданным именем не существует.";
return false;
}
string fileContent = null;
try{
fileContent = ReadAllContent(fileInfo);
}
catch(Exception ex){
msg = ex.Message;
return false;
}
// Возможно стоит добавить проверку на пустоту файла
// if(string.IsNullOrEmpty(fileContent)) { msg = "Файл не должен быть пуст." return false; }
switch(fileInfo.Extension)
{
case ".txt":
ProcessingTxtFile(fileContent);
break;
case ".html":
ProcessingHtmlFile(fileContent);
break;
default:
msg = "Неизвестный формат файла.";
return false;
break;
}
return true;
}
private string ReadAllContent(FileInfo fileInfo)
{
string text = "";
// Здесь так же написал вариант с оптимизацией чтения объёмного файла, что не обязательно, если не стоит таких задач.
if(fileInfo.Length < Int32.MaxValue)
{
using (FileStream fs = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.Read, FileShare.None))
using (BufferedStream bs = new BufferedStream(fs, Convert.ToInt32(fileInfo.Length)))
using (StreamReader sr = new StreamReader(bs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
text+=line;
}
}
}
else
{
using (StreamReader sr = fileInfo.OpenText())
{
string line;
while ((line = sr.ReadLine()) != null)
{
text+=line;
}
}
}
return text;
}
private void ProcessingTxtFile(string content) {/* ... */}
private void ProcessingHtmlFile(string content) {/* ... */}
}