Click here to Skip to main content
15,916,945 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this code for saving files into sql server

public byte[] ReadDoc(string document)
{
byte[] DocData = null;
DirectoryInfo dirInfo = new DirectoryInfo(document);
foreach (FileInfo f in dirInfo.GetFiles())
{
long DocFileLength = f.Length;
FileStream fs1 = new FileStream(document, FileMode.Open, FileAccess.Read);
BinaryReader br1 = new BinaryReader(fs1);
DocData = br1.ReadBytes((int)DocFileLength);
}

return DocData;

}
and on save button event I have

if (listOfLoadedFiles.Items.Count != 0)
{
byte[] fileData = null;

foreach (ListViewItem item in listOfLoadedFiles.Items)
{

string extension = Path.GetExtension(item.Text);

fileData = ReadDoc(item.Text);

daData2.InsertCommand = new SqlCommand("INSERT INTO Documents VALUES (@Documents, @patternID, @userID, @documentName, @extension)", cs);

daData2.InsertCommand.Parameters.Add("@Documents", SqlDbType.VarBinary).Value = fileData;
daData2.InsertCommand.Parameters.Add("@patternID", SqlDbType.NVarChar).Value = patternID.Text;
daData2.InsertCommand.Parameters.Add("@userID", SqlDbType.NVarChar).Value = ID.Text;
daData2.InsertCommand.Parameters.Add("@documentName", SqlDbType.NVarChar).Value = item.Text;
daData2.InsertCommand.Parameters.Add("@extension", SqlDbType.NVarChar).Value = extension;

cs.Open();
daData2.InsertCommand.ExecuteNonQuery();
cs.Close();

}

}
else
{

}

and the problem is when I am saving files from different folders, it seems that saved path in FileInfo remebers only the last

added file to listview (listOfLoadedFiles), and when I click Save button, i get error on line

long DocFileLength = f.Length; that file couldn't be found

any help, thank you
Posted

Before we look at that, and try to sort it out, what are you trying to do? You do realize that your ReadDoc method will return the data for the last file it finds in the folder you specify? So if there are six files, it will read them all, and return the final one - whichever that happens to be in the system your app is running in? And that there is a very good chance that it will fail for access denied reasons on a huge number of folders?
And that if you pass a filename as your code implies, it will fail anyway? And if it's a path, then your extension info will be wrong?
And that it could be replaced by File.ReadAllBytes if you specify the file you want to read rather than a path?


See OP comments below with code

Ok, so the ListView has individual file names in it?
So each ListViewItem is a single file, complete with it's path.
To read the file content:
C#
foreach (ListViewItem item in listOfLoadedFiles.Items)
    {
    string path = item.Text;
    if (!string.IsNullOrWhiteSpace(path) && File.Exists(path))
        {
        byte[] data = File.ReadAllBytes(path);
        long length = new FileInfo(path).Length;
        string extension = Path.GetExtension(path);
        ... continue and write the file to SQL.
        }
    }

And dump the ReadDoc method completely!
 
Share this answer
 
v2
Comments
shonezi 21-Nov-13 5:24am    
thank you Griff, you are right with all your questions. how can I change my ReadDoc code (please help me, I am in dead end)
OriginalGriff 21-Nov-13 5:35am    
What are your trying to pass to it, and what are you trying to do with that?
If you are trying to pass a specific file path, then DirectoryInfo is not much use.

(Sounds vague, I know - but remember I can't see your screen, so if you don't tell me I have to guess)
shonezi 21-Nov-13 5:47am    
you right, ok, this is what I am trying to do

I am saving files to sql server,

I have a form with btnSave, listview (listOfLoadedFiles), btnLoadFiles, folderbrowserdialog,

on btnLoadFiles click event I have this code, which works

openFileDialog2.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog2.Title = "Insert document";
openFileDialog2.FileName = "";
openFileDialog2.Filter = "All Files|*.*";

IntPtr hImgSmall; //the handle to the system image list
//IntPtr hImgLarge; //the handle to the system image list
string fName; // 'the file name to get icon from
string fName1;
SHFILEINFO shinfo = new SHFILEINFO();

listOfLoadedFiles.SmallImageList = imageList1;
listOfLoadedFiles.LargeImageList = imageList1;

//openFileDialog1.ShowDialog();

if (openFileDialog2.ShowDialog() != DialogResult.Cancel)
{
listOfLoadedFiles.BringToFront();
listView1.SendToBack();


fName1 = openFileDialog2.SafeFileName;
//Use this to get the small Icon
hImgSmall = Win32.SHGetFileInfo(fName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);

//Use this to get the large Icon
//hImgLarge = SHGetFileInfo(fName, 0,
// ref shinfo, (uint)Marshal.SizeOf(shinfo),
// Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);

//The icon is returned in the hIcon member of the shinfo struct
System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

imageList1.Images.Add(myIcon);

//Add file name and icon to listview

listOfLoadedFiles.Items.Add(fName1, nIndex1++);


}
so here I have loaded files to listview and on btnSave need to save them into sql server, when I choose files from same folder everything works fine, because as you said, the path is the same for all files, and the problem you already know
shonezi 21-Nov-13 5:51am    
public byte[] ReadDoc(string document)
{
byte[] DocData = null;
DirectoryInfo dirInfo = new DirectoryInfo(document);
foreach (FileInfo f in dirInfo.GetFiles())
{
long DocFileLength = f.Length;
FileStream fs1 = new FileStream(document, FileMode.Open, FileAccess.Read);
BinaryReader br1 = new BinaryReader(fs1);
DocData = br1.ReadBytes((int)DocFileLength);
}

return DocData;

}

private void btnSave_Click(object sender, EventArgs e)
{
if (listOfLoadedFiles.Items.Count != 0)
{
byte[] fileData = null;

foreach (ListViewItem item in listOfLoadedFiles.Items)
{

string extension = Path.GetExtension(item.Text);

fileData = ReadDoc(item.Text);

daData2.InsertCommand = new SqlCommand("INSERT INTO Documents VALUES (@Documents, @patternID, @userID, @documentName, @extension)", cs);

daData2.InsertCommand.Parameters.Add("@Documents", SqlDbType.VarBinary).Value = fileData;
daData2.InsertCommand.Parameters.Add("@patternID", SqlDbType.NVarChar).Value = patternID.Text;
daData2.InsertCommand.Parameters.Add("@userID", SqlDbType.NVarChar).Value = ID.Text;
daData2.InsertCommand.Parameters.Add("@documentName", SqlDbType.NVarChar).Value = item.Text;
daData2.InsertCommand.Parameters.Add("@extension", SqlDbType.NVarChar).Value = extension;

cs.Open();
daData2.InsertCommand.ExecuteNonQuery();
cs.Close();

}

}
else
{


}
shonezi 21-Nov-13 5:52am    
that's all the code I have
Load files into listview, and save
In your code that (I think) gets a directory path, and reads all the files in it: you are creating, and using, all the variables each time the 'foreach loop executes its inner code. So you "throw away" the contents of the byte array 'DocData, except for the last time the loop executes. I think that's probably the source of your problem.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900