|
Ian Uy wrote: I am wondering if there is a way to convert a certain file(.EXE,.JPG) to Binary/Byte
The files are already binary data. All files are always binary data, even text files are binary data. It's only when you read a text file as text that it becomes text, otherwise it's only bytes.
Reading a file is quite easy:
byte[] data = File.ReadAllBytes(@"c:\test.jpg");
Ian Uy wrote: For example, I have a certain Picture.jpg. I want to convert it to binary/Byte, and save it as a TEXT FILE.
You can't save binary data as text. If you want the binary data as text, you have to convert it, for example using base 64:
string dataText = Convert.ToBase64String(data);
Each character (which is a 16 bit unicode character) now contains 6 bits of information. Now you can save the string as a text file.
(Note that the text will be encoded to binary format (usually using utf-8 encoding) when saved as a file, as files always are binary.)
When you have read back the text file as a string, you can convert it back to the original data:
byte[] data = Convert.FromBase64String(dataText);
---
single minded; short sighted; long gone;
|
|
|
|
|
Thank you for the reply Sir Guffa.
Now that I have the data back to byte array. By using this:
byte[] data = Convert.FromBase64String(dataText);
How can I turn it back to c:\test.jpg
Thank you again.
|
|
|
|
|
Take a look at the File.WriteAllBytes method.
---
single minded; short sighted; long gone;
|
|
|
|
|
I have written a report to print labels which works quite well as long as a full sheet is to be printed. Unfortunately in the real world people rarely print full sheets of labels. Instead they need to be able to specify a column and row to begin printing.
The label report is actually a horizontal report that prints three rows then moves to the next column prints three rows and so on. The names and addresses are pulled from a SQL Server 2005 database.
Is there a way to send printer codes to the printer to position the print head before printing begins?
I've even thought about using dummy records to get the printer to skip to the right record, but I'm not sure how to do that or if it would even work.
Any suggestions are appreciated.
|
|
|
|
|
Roger CS wrote: Any suggestions are appreciated.
I suggest you do some reading about how to do printing[^]
|
|
|
|
|
Anyone here who actually knows how to do what I'm asking about?
|
|
|
|
|
Your description isn't very clear, so I'm guessing at it too. How about this[^].
|
|
|
|
|
Dave Kreskowiak wrote: Your description isn't very clear
I’ll try to be clearer. I am printing mailing labels. The sheet of labels has 3 columns and 10 rows (for a total of 30 labels). Normally people don't need to print exactly 30 labels or multiples of 30. Instead they may need to print 10, then later 6 more and so on. If the user starts with a fresh sheet and prints 10 labels, there will be 20 labels remaining. The next time the user prints labels they need to start printing at label 11. For this reason, the program allows the user a way to enter the row and column at which to start printing labels. In this case the user would enter row = 4 and column = 2.
I want to know how to start printing labels at row 4, column 2.
The information in the labels is pulled from a SQL Server 2005 database using a select query.
Thanks for the pointer to the KB article!
Roger
-- modified at 17:35 Saturday 13th October, 2007
|
|
|
|
|
led mike wrote: I suggest you do some reading about how to do printing
Yup, you were right. Everything I needed to know was there... I just had to extend PrintDocument and add some functionality.
Thanks,
Roger
|
|
|
|
|
Roger CS wrote: Thanks
See I did actually now something about it
Seriously though, one can never go wrong reading documentation. Even if it does not present your immediate solution you still gain knowledge.
|
|
|
|
|
How are you printing the labels now? Direct sending ESC keys to printer or using print document?
|
|
|
|
|
I wrote a report. I was just printing the report. I hadn't gotten any further than that when I posted this question. What I have learned since then is that I can print lables using the PrintDocument class. I just need to extend the functionality to meet my requirements.
|
|
|
|
|
HI,
I made a Form.
When a button is clicked, the main thread starts a timer and does some heavy tasks. When the tasks are finished, the main thread stops the timer.
What the timer does is just to update a textbox (like a progress bar to indicate the progress of the main thread). But the textbox is NOT updated until the main thread finishes its tasks (a pop-up dialog is shown and the main thread waits for a button-click in the dialog).
Would anyone help please?
Thanks!
|
|
|
|
|
|
Hi!
What you describe is just the way it is. The main thread is the only one responsible for updating the UI, i.e. triggering the controls to paint themselves.
Then the main thread is busy doing other things, the controls are not repainted.
When you write that you use a timer, then this information is not enough. There are at least 3 different timers I know of in the BCL, one doing its work on the main thread (System.Windows.Forms.Timer ) and the other two working on separate threads (for example, System.Timers.Timer ).
If you say that your UI isn't responsive while the timer is running, I guess you're using the first one.
The solution for this kind of problem is to let the "heavy task" run in a separate thread, thus freeing the main thread for updating the UI.
But beware - you cannot update your UI from a different thread than the main UI thread directly. You'll have to use Invoke() or BeginInvoke() for this.
Regards,
mav
--
Black holes are the places where God divided by 0...
|
|
|
|
|
Yes, I am using the Form's timer.
Thanks a lot for your help!
|
|
|
|
|
Hi all,
I have several methods, with many different signatures, that I would like to allow the user to cancel in the middle of their operation. This wouldn't be a backgroundworker situation, however---these are methods in my library that are called synchronously from a certain thread, and need to operate synchronously (i.e., the calling thread should be waiting on them to finish), then canceled from the UI thread. Also, since these methods by default operate just by a method call, and not any other invocation, I don't want to make them all conform to the backgroundworker's dowork event handler signature.
So, is there some kind of built-in way to do this, perhaps with an attribute? How would the method check that it's time to cancel? How can I specify, preferably at compile time of course, that only methods x, y, and z can be canceled?
Otherwise, my solution is as follows:
- If you want to call the method normally (without canceling capabilities), just call it.
- If you want to call a method in a cancelable fashion, call
object Controller.PerformOngoingOperation(method, string id, params object[] args) ; another thread can later call Controller.CancelOngoingOperation(string id) .PerformOngoingOperation checks that the method passed (more on that later) has the appropriate OngoingOperationAttribute ; if so, it invokes it. It also stores in an internal dictionary a map from ids to boolean "should cancel now" variables.- The method in question finds its ID. This is kludgy... it involves reflections to find the calling method, check if the calling method is
PerformOngoingOperation , and if so, ready the id parameter. - It then uses this id to performs a series of checks throughout its operation against that
internal map from ids to "should cancel now"; if at any point the should-cancel bit is true, it finishes what it's doing and returns. - Then,
PerformOngoingOperation will return the results of the method, whether canceled prematurely or not. So it acts just like invoking the method (good for users!), but can allow cancellation. - The should-cancel bit is set by
Control.CancelOngoingOperation(string id) , with consequences as above.
IF the above approach is reasonable---and it's very nice from a user's perspective, except for the upcoming detail---then I have a question. How should I pass the method to PerformOngoingOperation ? Is there any way to do so without awkwardness? What I mean is that, as far as I can tell, I want to use a delegate. This necessitates that the user of my library declare a new delegate type for every method he wants to call in a cancelable fashion! And he can't even declare delegate types locally; he has to pollute his class with them. Like this:
class C
{
delegate int annoying(int param1, bool param2, string param3);
void Method()
{
string id;
int retVal = (int)Control.PerformOngoingOperation(new annoying(Library.Object.Method), out id, param1, param2, param3);
}
}
I suppose an alternative is requiring that the delegate be of type MethodInvoker (basically void return type, no parameters), and forcing the user to do this:
int retVal;
string id = Control.PerformOngoingOperation((MethodInvoker)(new delegate() { retVal = Library.Object.Method(param1, param2, param3); }));
But that's awkward at best.
Ideally I would like to have something like this instead:
string id;
int retVal = Control.PerformOngoingOperation(Library.Object.Method, out id, param1, param2, param3);
Is that possible?
-Domenic Denicola- [CPUA 0x1337]
“I was born human. But this was an accident of fate—a condition merely of time and place. I believe it's something we have the power to change…”
|
|
|
|
|
|
I think the basic problem you are facing is that you are trying to introduce state (the cancel variable) into the methods. Would it be possible to put each method in a class? Something like
abstract class Operation
{
bool cancelIssued;
void Cancel() { cancelIssued = true; }
void Execute();
}
class A : Operation
{
int a; string b;
public A(int a, string b)
{
this.a = a;
this.b = b;
}
public override void Execute() { MethodA(a, b); }
void MethodA(int a, string b)
{
if (this.cancelIssued)
return;
}
}
This allows the user to do something like
A a = new A(1, "Foo")
Control.PerformOperation(a);
Control.PerformOperation(someOtherClassInstance);
a.Cancel()
from another thread.
|
|
|
|
|
That's actually a really good idea. However, I'd want to avoid having to create a new class for each ongoing operation, and I'd prefer to be able to leave the methods in their original class for the normal callers... hmm. There must be some way to hybridize this... if only methods were also objects, heh.
-Domenic Denicola- [CPUA 0x1337]
“I was born human. But this was an accident of fate—a condition merely of time and place. I believe it's something we have the power to change…”
|
|
|
|
|
Hi,
I was wondering if anyone could push me in the right direction on this one.
I got a file with multiple files inside it like an archive, its not compressed it just seems like the files are stacked inside the file.
I can read the headers of head indevidual file with a hex reader, so I have indetified that the file contain several wav files, some dds files and jpeg, avi etc.
what I have visioned is a loop that goes trough the file and each time it identifies a header it dumps that header and the following data to a file and continues to read on sortof splitting the file up again.
Im unsure if I should have a list of just the data headers im expecting to find or if I should make a struct with the structure setup of all the file spesification's im expecting and have the loop match against that.
Also what would be the most efficient way to go trough the file, its pretty large (about 4-500mb)?
structure example:
typedef struct _avimainheader {<br />
FourCC fcc;<br />
DWORD cb;<br />
DWORD dwMicroSecPerFrame;<br />
DWORD dwMaxBytesPerSec;<br />
DWORD dwPaddingGranularity;<br />
DWORD dwFlags;<br />
DWORD dwTotalFrames;<br />
DWORD dwInitialFrames;<br />
DWORD dwStreams;<br />
DWORD dwSuggestedBufferSize;<br />
DWORD dwWidth;<br />
DWORD dwHeight;<br />
DWORD dwReserved[4];<br />
} AVIMAINHEADER;
|
|
|
|
|
Do you have any other files that accompany this file? I'm asking because a data file like you are describing would commonly have an index, either embedded in the data file or in a separate file. If you had the index you could position to the offsets and read. If you don't have an index you'll probably have to read sequentially and detect headers as you go. As far as efficiency is concerned... don't optimize unless the method you're using is too slow. In that case you want to find the bottlenecks and open them up.
|
|
|
|
|
As far as I can tell its just that file, there are some compiled pyton files there that I have'nt had any luck prying information from, it might be that they hold a sort of a catalog but im unsure.
I have been playing around trying to extract the raw data, but I have some problems getting the loop to determine where the data ends and where a new header begins.
|
|
|
|
|
I am building a Windows Service and keep getting a System.IO.Exception {"The process cannot access the file 'J:\\Projects\\RTalarms_20071008.txt' because it is being used by another process."}.
Nothing has the file open. It is just sitting in the directory. The Bolded area is where the error occurs.
Any Idea why?
This the code;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Data.SqlClient;
namespace MCPAlarmMonitor
{
public partial class MCPAlarmMonitorService : ServiceBase
{
public MCPAlarmMonitorService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
fileSystemWatcher1.EnableRaisingEvents = true;
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
fileSystemWatcher1.EnableRaisingEvents = false;
}
private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
using (StreamReader reader = new StreamReader(e.FullPath)) {
string text = reader.ReadLine();
while (text != null)
{
text = text.TrimEnd(' ');
string[] tokens = text.Split(',');
InsertRecord(tokens);
text = reader.ReadLine();
}
}
}
private void InsertRecord(string[] tokens)
{
using (SqlConnection connection = new SqlConnection("server=localhost;database=MCPAlarms;integrated security=true"))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into AlarmsList values(@DateTime,@Address,@Location,@State,@notused1,@notused2,@AlarmMessage)";
for (int i = 0; i < 8; i++)
{
string parameterName = string.Format("@Column{0}", i + 1);
string parameterValue = tokens.Length > i ? tokens[i] : string.Empty;
command.Parameters.AddWithValue(parameterName, parameterValue);
}
connection.Open();
command.ExecuteNonQuery();
}
}
}
}
|
|
|
|
|
Your code is reacting to the Created event immediately after the file is created, but probably before the file is closed by the process that created it, so yes, the file is being held open with DenyShareAll while it's being written by the other process. By the time you realize it and look at the file, it's done being written and has been closed.
That's one of the pitfalls of the FSW. Your code has to be written to retry file operations if your going to start modifying the file while it's still being written. If you can't open the file, you'll have to wait a second and retry the operation. Keep retying until you either reach some retry limit your've put in, or the file successfully opens.
|
|
|
|
|