How to read .DAT files in a folder one by one - c#

I'm creating a software to get the data from .dat file and write those data in database. There are so many .dat files so I need to do a batch process. I'm currently reading one dat file by using this code
UDisk udisk = new UDisk();
byte[] byDataBuf = null;
int iLength;//length of the bytes to get from the data
string sPIN2 = "";
string sVerified = "";
string sTime_second = "";
string sDeviceID = "";
string sStatus = "";
string sWorkcode = "";
openFileDialog1.Filter = "1_attlog(*.dat)|*.dat";
openFileDialog1.FileName = "1_attlog.dat";//1 stands for one possible deviceid
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileStream stream = new FileStream(openFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Read);
byDataBuf = File.ReadAllBytes(openFileDialog1.FileName);
iLength = Convert.ToInt32(stream.Length);
lvSSRAttLog.Items.Clear();
int iStartIndex = 0;
int iOneLogLength;//the length of one line of attendence log
for (int i = iStartIndex; i < iLength - 2; i++)//modify by darcy on Dec.4 2009
{
if (byDataBuf[i] == 13 && byDataBuf[i + 1] == 10)
{
iOneLogLength = (i + 1) + 1 - iStartIndex;
byte[] bySSRAttLog = new byte[iOneLogLength];
Array.Copy(byDataBuf, iStartIndex, bySSRAttLog, 0, iOneLogLength);
udisk.GetAttLogFromDat(bySSRAttLog, iOneLogLength, out sPIN2, out sTime_second, out sDeviceID, out sStatus, out sVerified, out sWorkcode);
ListViewItem list = new ListViewItem();
list.Text = sPIN2;
list.SubItems.Add(sTime_second);
list.SubItems.Add(sDeviceID);
list.SubItems.Add(sStatus);
list.SubItems.Add(sVerified);
list.SubItems.Add(sWorkcode);
lvSSRAttLog.Items.Add(list);
bySSRAttLog = null;
iStartIndex += iOneLogLength;
iOneLogLength = 0;
}
}
stream.Close();
}
How can I read files one by one and transfer those data into database.
My database is - SMS
table is -
CHECKINOUT
columns -CHECKDate datetime
CHECKTime datetime
InOutMode int
Status varchar(50)
WorkCode varchar(50)
Memoinfo varchar(50)
sn int
sn2 int
Ip varchar(16)
Updated int

Given a folder path, you can use Directory.EnumerateFiles to get .dat files one by one:
string folder = #"D:\your\Folder";
foreach(var file in Directory.EnumerateFiles(
folder, // folder path
"*.dat" // file type you want
/*, SearchOption.AllDirectories*/)) // uncomment it if you want open files in subfolder
{
FileStream stream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read);
byDataBuf = File.ReadAllBytes(openFileDialog1.FileName);
iLength = Convert.ToInt32(stream.Length);
// Do your stuff here
stream.Close();
}

Related

How to scan two-sided (Duplex?) using WIA - C#

I'm writing a C # method that scans a lot of documents, but I need to scan these documents two-sided, ie for each sheet, scan the front and back of the document using the scanner's ADF. But I've tried all the ways I found on the internet and I could not. My code is below:
//user select the scanner
int indexScanner = Convert.ToInt32(Console.ReadLine());
// Connect to the first available scanner
var device = deviceManager.DeviceInfos[indexScanner - 1].Connect();
// Select the scanner
var scannerItem = device.Items[1];
int resolution = 150;
int width_pixel = 1250;
int height_pixel = 1700;
int color_mode = 1;
int adf_mode = 1;
int pages_mode = 1;
device.Properties["3096"].set_Value(pages_mode);
//device.Properties["3088"].set_Value(adf_mode);
scannerItem.Properties["3088"].set_Value(adf_mode);
AdjustScannerSettings(scannerItem, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode);
CommonDialogClass dlg = new CommonDialogClass();
object scanResult = dlg.ShowTransfer(scannerItem, FormatID.wiaFormatJPEG, true);
if (scanResult != null)
{
ImageFile image = (ImageFile)scanResult;
string filename = "scan.jpeg";
if (File.Exists(filename))
File.Delete(filename);
image.SaveFile(filename);
}
scanResult = dlg.ShowTransfer(scannerItem, FormatID.wiaFormatJPEG, true);
if (scanResult != null)
{
ImageFile image = (ImageFile)scanResult;
string filename = "scan1.jpeg";
if (File.Exists(filename))
File.Delete(filename);
image.SaveFile(filename);
}

Read Image file metadata

I want to upload an image file and then extract its basic information (author, dimensions, date created, modified, etc) and display it to the user. How can I do it.
A solution or reference to this problem in asp.net c# code would be helpful. But javascript or php would be ok as well.
Check this Link. You will get more Clearance about GetDetailsOf() and its File Properties based on the Win-OS version wise.
If you want to use C# code use below code to get Metadata's:
List<string> arrHeaders = new List<string>();
Shell shell = new ShellClass();
Folder rFolder = shell.NameSpace(_rootPath);
FolderItem rFiles = rFolder.ParseName(filename);
for (int i = 0; i < short.MaxValue; i++)
{
string value = rFolder.GetDetailsOf(rFiles, i).Trim();
arrHeaders.Add(value);
}
C# solution could be found here:
Link1
Link2
Bitmap image = new Bitmap(fileName);
PropertyItem[] propItems = image.PropertyItems;
foreach (PropertyItem item in propItems)
{
Console.WriteLine("iD: 0x" + item.Id.ToString("x"));
}
MSDN Reference
C# Tutorial Reference
try this...
private string doUpload()
{
// Initialize variables
string sSavePath;
sSavePath = "images/";
// Check file size (mustn’t be 0)
HttpPostedFile myFile = FileUpload1.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
//**************
//lblOutput.Text = "No file was uploaded.";
return null;
}
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
//**************
//lblOutput.Text = "The file must have an extension of JPG";
return null;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an
// incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}
// Save the stream to disk
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
return sFilename;
}

How split mp3 using Naudio?

How can i cut a certain time of mp3 file and convert it to wave with N audio with out save any file in hard disk? (i want result in byte array!)
Refer Following Code:
string nMP3Folder = "FOLDER PATH";
string nMP3SourceFilename = "SOURCE MP3 FILENAME";
string nMP3OutputFilename = "YOUR OUTPUT MP3 FILENAME";
using (Mp3FileReader rdr = new Mp3FileReader(nMP3Folder + nMP3SourceFilename))
{
int count = 1;
Mp3Frame objmp3Frame = reader.ReadNextFrame();
System.IO.FileStream _fs = new System.IO.FileStream(nMP3Folder + nMP3OutputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
while (objmp3Frame != null)
{
if (count > 500) //retrieve a sample of 500 frames
return;
_fs.Write(objmp3Frame.RawData, 0, objmp3Frame.RawData.Length);
count = count + 1;
objmp3Frame = rdr.ReadNextFrame();
}
_fs.Close();
}
Also refer following question to get more links:
Trim an MP3 Programatically

Split file from a url

I had some codes to split files and join ,Now am trying to make a program that split file from a url and download , for example http://tegos.ru/new/mp3_full/David_Guetta_feat_Ne-Yo_and_Akon_-_Play_Hard.mp3 spilit this file in two pieces and download
my split-er code
Byte[] byteSource = System.IO.File.ReadAllBytes(FileInputpath);
FileInfo fiSource = new FileInfo(txtPath.Text);
int partsize = (int)Math.Ceiling((double)(fiSource.Length / OutputFiles));
int fileOffset = 0;
string currPartPath;
FileStream fsPart;
int sizeReamining = (int)fiSource.Length;
for (int i = 0; i < OutputFiles; i++)
{
currPartPath = FolderOutputPath + "\\" + fiSource.Name + "." + String.Format(#"{0:D4}", i) + ".gparts";
if (!File.Exists(currPartPath))
{
fsPart = new FileStream(currPartPath, FileMode.CreateNew);
sizeReamining = (int)fiSource.Length - (i * partsize);
if (sizeReamining < partsize)
{
partsize = sizeReamining;
}
fsPart.Write(byteSource, fileOffset, partsize);
fsPart.Close();
fileOffset += partsize;
}
}
Use HttpWebRequest to get a stream from the specified url.
When you have the stream, you can use your previous code.
Download/Stream file from URL - asp.net

Insert signature data into SQL Server in MVC 2 C#

I have working code that uses signature pad data to create and save a signature bmp image to a file location. My question is: how can I modify this code to insert the image into a SQL Server 2008 image field?
The following from my Controller obtains signature data from a signature tablet and creates a bmp image and saves it to a file location.
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public ActionResult SaveSignature2(IPrincipal principal) {
int userId = ((ScoutIdentity)principal.Identity).UserId.Value;
//Put user code to initialize the page here
SIGPLUSLib.SigPlus sigObj = new SIGPLUSLib.SigPlus();
sigObj.InitSigPlus();
sigObj.AutoKeyStart();
string visitorname = Request.Form["visitorname"];
visitorname = visitorname.Replace(" ", ""); //combines the first name with last name with no spaces
visitorname = visitorname.Trim();
string thevrvIDstr = Request.Form["vrvID"];
int thevrvID = Convert.ToInt32(thevrvIDstr);
//use the same data to decrypt signature
sigObj.AutoKeyData = Request.Form["SigText"];
sigObj.AutoKeyFinish();
sigObj.SigCompressionMode = 1;
sigObj.EncryptionMode = 2;
//Now, get sigstring from client
//Sigstring can be stored in a database if
//a biometric signature is desired rather than an image
sigObj.SigString = Request.Form["hidden"];
if (sigObj.NumberOfTabletPoints() > 0) {
sigObj.ImageFileFormat = 0;
sigObj.ImageXSize = 500;
sigObj.ImageYSize = 150;
sigObj.ImagePenWidth = 8;
sigObj.SetAntiAliasParameters(1, 600, 700);
sigObj.JustifyX = 5;
sigObj.JustifyY = 5;
sigObj.JustifyMode = 5;
long size;
byte[] byteValue;
sigObj.BitMapBufferWrite();
size = sigObj.BitMapBufferSize();
byteValue = new byte[size];
byteValue = (byte[])sigObj.GetBitmapBufferBytes();
sigObj.BitMapBufferClose();
System.IO.MemoryStream ms = new System.IO.MemoryStream(byteValue);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
String path;
path = System.AppDomain.CurrentDomain.BaseDirectory;
path = path + "/uploadFiles/Signatures/"+thevrvIDstr+".bmp";
img.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);
ViewData["Result"] = ("Image saved successfully to " + path);
}
else {
ViewData["Result"] = "signature has not been returned successfully!";
}
ViewData["Result"] = sigObj.SigString;
//return RedirectToAction("vrSignIn");
return View();
}
I also have code elsewhere in my controller that gets an uploaded file and inserts it into the database. This code works OK.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadTempFiles(string id, string u)
{
//this method temporarily stores files
string userIdString = Cryptographer.DecryptSymmetric("RijndaelManaged", SecurityImpl.UrlToBase64(u));
int userId = Convert.ToInt32(userIdString);
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
int contentlength = file.ContentLength;
byte[] b = new byte[contentlength];
Stream s;
s = file.InputStream;
s.Read(b, 0, contentlength);
VisitRequest.AddVisitorSignature(userId, b);
}
}
return View("UploadFiles");
}
I'm thinking that I can use some part of the second code to interrupt the image creation process in the first code and insert the image into the database INSTEAD of saving the image to a file location. I don't know how to do that.
I had same problem, and I solved it:
Comment these three lines:
//path = System.AppDomain.CurrentDomain.BaseDirectory;
//path = path + "/uploadFiles/Signatures/"+thevrvIDstr+".bmp";
//img.Save(path, System.Drawing.Imaging.ImageFormat.Bmp);
Convert image to String data (assumed that your variable 'strSignature' was declared before):
strSignature = img.ToString();
Save it with your Stored Procedure.
Hope this help you!

Categories

Resources