Class File and Directory in C#.........................................
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace TestFile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// invoked when user presses key...............
private void
txtinput_KeyDown(object sender, KeyEventArgs e)
{
//determine whether user pressed Enter Key...
if (e.KeyCode == Keys.Enter)
{
string filename = txtinput.Text;
if (File.Exists(filename))
{
GetInformation(filename);
StreamReader stream = null; //declare
StreamReader.....
try
{
stream
= new StreamReader(filename);
txtoutput.AppendText(stream.ReadToEnd());
}
catch (IOException)
{
MessageBox.Show("Error
reading from File", "File
Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//determine whether filename is a Directory...............
else if(Directory.Exists(filename))
{
GetInformation(filename);
string[] directoryList = Directory.GetDirectories(filename);
txtoutput.AppendText("Directory Contents:\n");
foreach (var directory in directoryList)
{
txtoutput.AppendText(directory
+ "\n");
}
}
else
{
MessageBox.Show(txtinput.Text + " "+" does not exist", "File Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void
GetInformation(string filename)
{
txtoutput.Clear();
txtoutput.AppendText(filename
+ "
"+"is exists\n");
//output when file or dirctory was created.............
txtoutput.AppendText("Created:" + File.GetCreationTime(filename)
+ "\n");
//output when file or dirctory was modified.............
txtoutput.AppendText("Last Modified:" + File.GetLastWriteTime(filename) + "\n");
//output when file or dirctory was accessed.............
txtoutput.AppendText("Last Accessed:" + File.GetLastAccessTime(filename) + "\n");
}
}
}
0 comments:
Post a Comment