please can anyone help me i'm still figuring C# out, I have on my main form a datagridview and currently saves the uploaded files info there, but i want to do a check to see if the file exists don't upload if it does upload but honestly i'm struggling to understand the differences between fileinfo, directoryinfo, and how to work with it please have a look at my code, Thanks in advance!
string sqlSt = "Insert into Documents (CategoryID, PathofDocument,DocumentName,FileSize,FileExtension,AddedBy,LastActioned) values (@CategoryID,@FilePath,@FileName,@FileSize,@FileExtension,@AddedBy,@LastActioned)";
OpenFileDialog fi = new OpenFileDialog();
//DialogResult result = fi.ShowDialog();
fi.Filter = "allfiles (*.*)|*.* |Text files(*.txt)|*.txt | Excel Files (*.xls)| *.xls |EmailFiles (*.msg) | *.msg";
string fileio = fi.FileName;
FileInfo file = new FileInfo(fileio);
if (fi.ShowDialog() != DialogResult.OK)
{
if (file.Exists(,fileio))
{ }
// MessageBox.Show("File Already exist" + file.FullName);
}
else
if (file.Exists != true)
{
using (SqlConnection Conn = new SqlConnection(Connstring))
{
using (SqlCommand cmd = new SqlCommand(sqlSt, Conn))
{
Conn.Open();
cmd.Parameters.AddWithValue("CategoryID", treeView1.SelectedNode.Tag);
cmd.Parameters.AddWithValue("@FilePath", Path.GetFullPath(fi.FileName));
cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(file.Name));
cmd.Parameters.AddWithValue("@FileSize", file.Length / 1024);
cmd.Parameters.AddWithValue("@FileExtension", file.Extension);
cmd.Parameters.AddWithValue("@AddedBy", UserCon.Text);
cmd.Parameters.AddWithValue("@LastActioned", file.LastAccessTime);
cmd.ExecuteNonQuery();
SetValueforAddedB = UserCon.Text;
SetValueforType = Typtxt.Text;
Conn.Close();
}
}
File
has a static method which you can use to see if a file exists.
if (File.Exists("path"))
{
// upload code
}
else
{
// show message or whatever
}
i'm struggling to understand the differences between fileinfo, directoryinfo
FileInfo
is used for interacting and doing work on files. DirectoryInfo
is used for interacting and doing work with folders (directories).
If you are performing a single operation on a file, then use the static class File
. The same goes for Directory
. However, if you are doing multiple operations such as check if file exists, then read the file, then change the file, then save the file, then in that case use FileInfo
.
File
and Directory
are static classes. FileInfo
and DirectoryInfo
are non static so you can create an instance, keep the instance and do all the operations on the instance.