Visual Studio | WPF > 파일 save, load > System.IO.File 사용

운영 환경
Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2

관련



System.IO.File 클래스

처리 개요


  • save
  • List<string>에서 목록화
  • WriteAllLines()에서 쓰기

  • load
  • ReadAllLines()에서 읽기
  • foearch에서 모든 항목 표시
  • 인덱스로 특정 항목 표시


  • code



    MainWindow.xaml
    <Window x:Class="_171114_t1200_fileWriteRead.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:_171114_t1200_fileWriteRead"
            mc:Ignorable="d"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button Name="B_fileIO" Width="100" Height="30" Content="file IO" Click="B_fileIO_Click"/>
        </Grid>
    </Window>
    

    MainWindow.xaml.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace _171114_t1200_fileWriteRead
    {
        /// <summary>
        /// MainWindow.xaml の相互作用ロジック
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();            
            }
    
            private readonly string kFilename = "test_171114.txt";
    
            private void fileWrite()
            {
                var datlst = new List<string>();
                for (int loop = 0; loop < 10; loop++)
                {
                    datlst.Add("3.141592, 2.7182");
                }
                System.IO.File.WriteAllLines(kFilename, datlst.ToArray());
            }
            private void fileRead()
            {
                // 1. read all lines
                var datlst = System.IO.File.ReadAllLines(kFilename);
                foreach(var elem in datlst)
                {
                    Console.WriteLine(elem);
                }
                // 2. show specific line
                Console.WriteLine("--- [5] ---");
                Console.WriteLine(datlst[5]);
            }
    
            private void B_fileIO_Click(object sender, RoutedEventArgs e)
            {
                fileWrite();
                fileRead();
            }
        }
    }
    

    좋은 웹페이지 즐겨찾기