.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
MarieAdela
Imran Ghani
Post New Web Links

Reading strings from a binary file

Posted By:      Posted Date: September 29, 2010    Points: 0   Category :.NET Framework
 

I am tasked with reading various files that were saved to disk by a Visual Basic 4 application.

I've started with the easiest of the files, which contains one or more strings, each 128 bytes in length.

And so I wrote the following code to put these strings in a list:

 

Console.WriteLine("========== START ==========");

var list = new List<string>();

var fileStream = new FileStream("(Filename)", FileMode.Open);
	
var bytes = new byte[128];
while (true) {
 if (fileStream.Read(bytes, 0, bytes.Length) == 0) break;
 list.Add(System.Text.Encoding.ASCII.GetString(bytes));
}

foreach (var s in list) Console.WriteLine(s);

fileStream.Close();

Console.WriteLine("========== END ==========")


View Complete Post


More Related Resource Links

Reading Binary file

  

Hi All, 

 I am using BinaryReader class to read binary file.But I am facing problem while reading number of  bytes from it.

I have written code to read only 2 bytes from it,it works well on my machine and read only 2 bytes,but when I deployed that code on server machine it read 4 bytes from file.Whats wrong in the code?Is it due to processor i.e.. 32 bit processor/64 bit processor I am using?

Please provide solution or any link for it ASAP..

Thanks in advance

Vaibhav

 

 


Create excel file from Binary data on SqlServer

  

Hi,

My requirement is that i upload an excel file then i need to validate that data.

Approach

1. Uploading file using using upload control saving binary in SqlServer

2. Then i am creating file from binary data  on Sql Server using below command and then using OPENROWSET to dump data to Sql table

3. Then reading Sql Table row wise and validating data.

 

Alter Procedure spUploadExcelFile
(
  @PKID int,
  @BatchID int
)
AS

BEGIN

	Declare @VarBin varbinary(max)
	Declare @FileName varchar(100)
	DECLARE @sql nvarchar(MAX)
                DECLARE @errMsg nvarchar(MAX)
	DECLARE @ObjectReturn INT
	DECLARE @ErrorSource VARCHAR(255)
	DECLARE @ErrorDesc VARCHAR(255)
	DECLARE @ObjectToken INT

	Select @VarBin  = Content , @FileName = [FileName] from MultilangBinaryData Where PKID = @PKID
	SET @FileName = 'C:\'  + @FileName
 
	EXEC sp_OACreate 'ADODB.Stream' @ObjectToken OUTPUT
	EXEC sp_OASetProperty @ObjectToken, 'Type', 1
	EXEC sp_OAMethod @ObjectToken, 'Open'
	EXEC sp_OAMethod @ObjectToken, 'Write', NULL, @VarBin
	EXEC sp_OAMethod @ObjectToken, 'SaveToFile', NULL, @FileName, 2
	EXEC sp_OAMethod @ObjectToken, 'Close'
	EXEC sp_OADestroy @ObjectToken  
	
	SET @sql = 'INSERT INTO dbo.UserBulkData SELECT 0,NULL,'+ @BatchI

reading excel file problem

  

Hi,


i have 200 rows in my excel file. im using OleDbConnection to read the excel file.

The problem is that it will read all the blank rows from row 200 onwards. Is there a configuration im missing ? or is there a way to import all rows that has data? Here's some of my code.


string excelConnectionString =
               "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source=" + filePath + ";" +
                "Extended Properties=Excel 8.0";

OleDbConnection excelConnection =
                    new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO'");


OleDbCommand cmd = new OleDbCommand("Select * from [list$]",excelConnection);







Reading an excel file

  

Hi,

i am trying to read an excel file.

when i read the entire file, it works fine.

but when i try to read a single column, i get the following exception message:

"Could not find installable ISAM".

the code i am using is:

string  connString = "Provider=Microsoft.ACE.OLEDB.12.0;" +  

 

"Data Source="+ fileName + ";" +

 

"Extended Properties=Excel 12.0;HDR=Yes";

OleDbConnection oledbConn = new OleDbConnection(connString);

 

try

{

// Open connection

oledbConn.Open();

 

// Create OleDbCommand object and select data from worksheet Sheet1

OleDbCommand cmd = new OleDbCommand

reading some strange file

  
hi all,I have a file that i want to read created by a program from another company.I fi open the file in notepad it has all kind of funny chars in it, i tried different ways of reading it in vb.net but the funny chars stay.Anyone has any idea how to read something like this?this is an extract from the file  Z "f 2006/05/19 13:44:28 < ----------- uStreetname 91 1745 Opwijk                                                                                  ' 590208356329 SLIN3f )lÿ%g: )' 29.11.2005grtz & thnx to anyone who looked into this.bjorn

Problem when using Activator.CreateObject and reading App.Config file

  
Hello, this is the scenario. I have an application that load at runtime severals dll. these dll are actually "adapters" that wraps calls to web services, database and so on. The app.config of the "main" application stores in config sections all information necessary to each adapter (i.e.Web ServiceURL..) and I have created inside each adapter a class to ready those values the loading at run time the DLL has been implemented by storing all necessary types into a dictionary of generics and when I need to instanciate it I call the Activate.CreateObject and I pass the specific type (I means the name of the Adapter class) The problem is that the adapter class itself is not able to get the config value because ConfigSection has not been initialized. If I write: IInterfaceAdap adapt = new myAdapter() -> I read the config data IInterfaceAdap adapt = (IInterfaceAdap)Activator.CreateObject (type) -> now way to read the data stored in the App.Config. I think that I undertood the problem but I'm not able to find a workaround to read data store in the app.config!! I need help please!!  

How to load binary file asynchronously

  
I need to be able to download file from local disk or UNC path asynchronously. I've tried to use FileStream, but not sure what is the best way to read file by small chunks and combine them together then. Btw, does it make sense to download file by small chunks? Here is what I tried: byte[] _content; void Start(){ FileInfo fi = new FileInfo(path); if(fi.Exists) { FileStream fs = new FileStream(path, FileMode.Open); var stateObject = new State(fs, fi.Length); fs.BeginRead(stateObject.Buffer, 0, (int)stateObject.BufferSize, new AsyncCallback(EndReadCallback), stateObject); } } ... public void EndReadCallback(IAsyncResult asyncResult) { State state = (State)asyncResult.AsyncState; int readCount = state.FStream.EndRead(asyncResult); //store bytes inside class instance this._content = state.Buffer; //close stream state.FStream.Close(); if(FileLoaded != null) { FileLoaded.Invoke(_content); } } Thanks in advance, Paul.

reading excel file without saving to disk first

  
Having an issue.  I need to be able to read an excel file from a file upload control but I can not save the file to disk first, it must be done in memory.string excelConnectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="; excelConnectionstring += filePath.Replace("/", "\\"); excelConnectionstring += ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"; OleDbConnection con = new OleDbConnection(excelConnectionstring); OleDbDataAdapter da = new OleDbDataAdapter();Above is my code for reading the data file if it IS saved to disk, but again, I have to be able to do this without saving the file to disk, it must be done in memory.  I have not been able to find any sample code anywhere on how to do this from memory, everything seems to force the file be uploaded, saved to disk, and then read in the connection string, which again I can not do.Any advise would be great, thanks in advance.  I'm really in a bind here.

Read Binary Data which is nothing but a Zip file and unzip through SSIS 2005 SP2

  
Hi ALL, I need some help in developing a task. I have a source database which is Oracle and it has a ZIP file stored inside the database in Binary format. When I move this data into the sql server 2005 database I get the data as binary data. Now the task begins with SSIS, I need to read the binary data which gives us a zip file and then unzip this zip file and read the XML data which is present inside the Zip file. I beleive some one might have already developed this task can you share the solution with us. Note: As this has to be moved into production I dont have permission to use third party tools like Cozy roc or install winrar.exe and simpy calling this exe from the execute process task in SSIS.  Raju

Error reading .config file in Windows Forms app - Access is denied

  
I'm attempting to read a connection string from a .config file in a Windows Forms app on a test laptop. A previous version of the application worked just fine, but now I get a configuration exception thrown - "Configuration system failed to initialize." The inner exception message says - "An error occurred loading a configuration file: Access is denied". The user I'm logged in as is in the Administrators group and there's no obvious problems with the config file. The same config file works just fine on my dev machine so it's not an issue with ordering of the XML. Any ideas would be greatly appreciated.If a response to your question is helpful or answers it please mark it as such!

Error reading .config file in Windows Forms app - Access is denied

  
I'm attempting to read a connection string from a .config file in a Windows Forms app on a test laptop. A previous version of the application worked just fine, but now I get a configuration exception thrown - "Configuration system failed to initialize." The inner exception message says - "An error occurred loading a configuration file: Access is denied". The user I'm logged in as is in the Administrators group and there's no obvious problems with the config file. The same config file works just fine on my dev machine so it's not an issue with ordering of the XML. Any ideas would be greatly appreciated.If a response to your question is helpful or answers it please mark it as such!

Inserting a Binary file in SQL Server 2000

  
Hi all, I want to store a native binary file into the DB having the column datatype as 'image', in SQL Server 2000, through SQL Query. I have found the solution for the case of 2005, thet is using the OPENROWSET and BULK. Can you please help me out in constructing the SQL or TSQL Query for performing that operation? Thanks a Bunch in Advance :)

Insertion of a Binary File in SQL Server 2000

  
Hi all, I want to insert a binary file into the SQL Server 2000. The type of the column reserved for the file is of 'image' datatype. I have found the solution for the SQL Server 2005 and later, using the open rowset. Can you please give me a SQL/T-SQL Query for the operation? Thanks a bunch in advance :)

Reading each record from a text file and sending email

  
Hi All, I have a text file (CSV) which has only three fields (Name, Email, SendYN). I want to read each record from this text file and send email to those records where SendYN field has Y. I had created Flat File connection and a Flat File source in a data flow which uses Flat file connection. Now I stuck how to move further. Which control I need to add and where to identify whether SenderYN = Y and how to send email? I am new to SSIS. Thanks.

Reading from Excel file : win form

  
Hi All, I have the following requirement  There are 10 Excel files in a folder.Each excel file contains only 1 column which contains severeal IDs listed. Now, I want to read those IDs in each & every excel file. How do I get the count of number of excel files present in that folder?? After getting the count, how do I read each Id present in that file?? Any help will be greatly apprecited.. Thanks, Alex

WCF Reading Endpoint Behaviors from a web.config file

  

Hi

I've got a WCF service which has multiple clients that it connects to.

What I want to do is to create the clients dynamically the WCF services consumes.

Creating the clients by inheriting from the `ServiceFactory<TChannel>` class is done and very simple. What I'm struggling with is how to read Endpoint behaviours from the `web.config` file and add them to the clients?

Code file

    BasicHttpBinding binding = new BasicHttpBinding(bindingConfigName);
    EndpointAddress endpoint = new EndpointAddress(endpointUrl);
    ChannelFactory<IShoppingSoap> clientEndpoint = new ChannelFactory<IShoppingSoap>(binding, endpoint);
   
    base.Endpoint.Behaviors.Add(*Get the behavior from the config file*);
    return base.CreateChannel();

`Web.config` file :

    <behaviors> 
        <endpointBehaviors> 
           <behavior name="EndpointBehaviour_GmCustom">
             <dataContractSerializer maxItemsInObjectGraph="2147483646" /> 
      

How to send binary data ( ogg audio file) using a web service?

  

Hi folks, I would appreciate any help or guidance on this topic:

How can I receive binary data (specifically an ogg audio file) using a WCF4 service?

The general idea is to define and host a WCF service inside IIS that returns an audio file (ogg file)

I have read some info related with using ByteStreamMessageEncodingBindingElement class to achieve this, also I read some topic related on using MTOM to attach a binary file. It seems that it can be several ways or approaches to achieve this.

So any guidance on the themes and/or examples for the better way to solve this point would be very appreciated.

Thanks in advance.

Carlos


cortega
Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend