Сохранение даты в текстовом файле - PullRequest
0 голосов
/ 10 марта 2011

Я занимаюсь разработкой небольшого приложения для Windows Phone.Необходимо сохранить текущую дату в качестве имени текстового файла.Прямо сейчас у меня есть следующий код:

{
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            isf.CreateDirectory("Data");
            StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream("Data\\myFile.txt", FileMode.Create, isf));
            sw.WriteLine(textBox1.Text);
            sw.Close();
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(new IsolatedStorageFileStream("Data\\myFile.txt", FileMode.Open, isf));
                textBlock1.Text = sr.ReadLine();
                sr.Close();
            }

            catch
            {
                textBox1.Text = "When you make a Journal entry, it will be displayed here.";
            }
        }
        private void textBlock1_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            isf.CreateDirectory("Data");
            StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream("Data\\myFile.txt", FileMode.Create, isf));
            sw.WriteLine(textBox1.Text);
            sw.Close();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {

        }

        private void textBlock1_Loaded(object sender, RoutedEventArgs e)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(new IsolatedStorageFileStream("Data\\myFile.txt", FileMode.Open, isf));
                textBlock1.Text = sr.ReadLine();
                sr.Close();
            }

            catch
            {
                textBlock1.Text = "When you make a Journal entry, it will be displayed here.";
            }
        }

Извините, функция "Код для вставки" не нравится моему коду.

Редактировать: Благодаря тому, кто / что исправил "ВставитьКод "функция.

Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

1 голос
/ 10 марта 2011

Вместо использования жестко заданного myFile.txt, просто создайте имя файла, используя DateTime.Today. Например:

string fileName = DateTime.Today.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);

Тогда вы можете создать свой StreamWriter:

StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream("Data\\" + fileName, FileMode.Create, isf));
0 голосов
/ 10 марта 2011

Мне кажется, я понимаю ваш вопрос. Вы хотите создавать новый текстовый файл каждый день и назовите файл как-нибудь как «03-09-2011.txt».

Вы можете сделать:

var fileName = string.Format("{0:MM-dd-yyyy}.txt", DateTime.Now);

Это получит имя файла, как я упоминал выше.

Возможно, я бы также использовал Path.Combine:

IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
var directory = "Data";
isf.CreateDirectory(directory);
var fileName = string.Format("{0:MM-dd-yyyy}.txt", DateTime.Now);
StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream(Path.Combine(directory, filName), FileMode.Create, isf));
sw.WriteLine(textBox1.Text);
sw.Close();

Это позаботится о добавлении "\" между путями, и, таким образом, вы разделите имя каталога и имя файла (мне всегда кажется, что они понадобятся позже).

Это дает дополнительное преимущество, которое вы можете легко добавить или добавить к имени:

var fileName = string.Format("This is the file for {0:MM-dd-yyyy}.txt", DateTime.Now);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...