.NET 4.x Считывание текстового файла команда Windows тип - C#
Формулировка задачи:
Здравствуйте! Помогите пожалуйста отредактировать код, иначе голова сейчас взорвется! Сложности вызывают: 1)Не могу сообразить как сделать так чтобы при вызове справки "help" он дальше предложил указать путь к считываемому документу. 2)Надо сделать так чтобы при вводе [диск:][путь]\*.txt считывал все txt документы. Вот код:
using System;
using System.Text;
using System.IO;
namespace XXX
{
class Type
{
const string h = "\n Type[диск:][путь]имя_файла";
static void Main(string[] args)
{
string s = "", pat = "", path = "", line;
int slash = 0;
Console.Write("\n Укажите путь к документу");
Console.WriteLine("\n для вывода справки введите ? -? help");
Console.Write(" Путь к документу: ");
s = Console.ReadLine();
if (s=="?"||s== "-?"||s=="help")
{
Console.WriteLine(h);
}
char[] p = s.ToCharArray();
for (int i = p.Length - 1; i > 0; i--)
{
if (p[i] == '*')
{
for (int j = i; j > 0; j--)
if (p[j] == '\\')
{
slash = j;
break;
}
for (int j = slash + 1; j < p.Length; j++)
pat += p[j];
for (int j = 0; j < slash + 1; j++)
path += p[j];
break;
}
}
try
{
string[] dirs = Directory.GetFiles(path, pat);
foreach (string dir in dirs)
{
line = R(dir);
}
if (pat == "")
{
line = R(s);
}
}
catch (Exception d)
{
Console.WriteLine("Файл не может быть прочитан:");
Console.WriteLine(d.Message);}
Console.ReadLine();
}
private static string R(string s)
{
string line = "";
StreamReader chet = new StreamReader(s, Encoding.GetEncoding("windows-1251"));
line = chet.ReadLine();
while (line != null)
{
Console.WriteLine("\n");
Console.WriteLine(line);
line = chet.ReadLine();
}
chet.Close();
return line;
}
}
}Решение задачи: «.NET 4.x Считывание текстового файла команда Windows тип»
textual
Листинг программы
try
{
Console.Write("Введите путь:"); // C:\Downloads\*.txt
string path = Console.ReadLine();
string folder = path.Substring(0, path.LastIndexOf("\\")); // копировать из path символы до последнего слеша
string ext = path.Substring(path.LastIndexOf("\\") + 1); // все, что после последнего слеша, т.е. *.txt
DirectoryInfo dir = new DirectoryInfo(folder);
if (dir.GetFiles(ext, SearchOption.TopDirectoryOnly).Length == 0)
{
Console.WriteLine(string.Format("Файлы с расширением \"{0}\" в директории \"{1}\" не найдены", ext, folder));
}
else
{
foreach (FileInfo file in dir.GetFiles(ext, SearchOption.TopDirectoryOnly)) // поиск txt файлов в папке folder
{
// для каждого из найденного файла
StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8);
// считываем файл в строку text
string text = reader.ReadToEnd();
reader.Close();
Console.WriteLine(text); // выводим на экран
}
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}