I am trying to hide text file into image with c#
void HideTextFileIntoImage(string TextPath, string ImagePath, string NewFilePath)
{
string[] Text = File.ReadAllLines(TextPath);
string[] Image = File.ReadAllLines(ImagePath);
File.Create(NewFilePath).Close();
string[] NewFile = new string[Text.Length + Image.Length];
for (int i = 0; i < Image.Length; i++)
{
NewFile[i] = Image[i];
}
for (int i = 0; i < Text.Length; i++)
{
NewFile[i + Image.Length] = Text[i];
}
StreamWriter sw = new StreamWriter(NewFilePath);
for (int t = 0; t < NewFile.Length; t++)
{
sw.WriteLine(NewFile[t]);
}
sw.Close();
}
But I can't see image after using it. What wrong?
You're trying to treat binary data as though it were text.
Try this instead (completely untested):
void HideTextFileIntoImage(string TextPath, string ImagePath, string NewFilePath)
{
var textBytes = File.ReadAllBytes(TextPath);
var imageBytes = File.ReadAllBytes(ImagePath);
using (var stream = new FileStream(NewFilePath, FileMode.Create)) {
stream.Write(imageBytes, 0, imageBytes.Length);
stream.Write(textBytes, 0, textBytes.Length);
}
}
Related
I have this function in Node.js
let inPath = process.argv[2] || 'file.txt';
let outPath = process.argv[3] || 'result.txt';
fs.open(inPath, 'r', (errIn, fdIn) => {
fs.open(outPath, 'w', (errOut, fdOut) => {
let buffer = Buffer.alloc(1);
while (true) {
let num = fs.readSync(fdIn, buffer, 0, 1, null);
if (num === 0) break;
fs.writeSync(fdOut, Buffer.from([255-buffer[0]]), 0, 1, null);
}
});
});
What would be the equivalent in C#?
My code so far. I do not know what is the equivalent code in C# to minus byte of a character. Thank you in advanced!
var inPath = "file.txt";
var outPath = "result.txt";
string result = string.Empty;
using (StreamReader file = new StreamReader(#inPath))
{
while (!file.EndOfStream)
{
string line = file.ReadLine();
foreach (char letter in line)
{
//letter = Buffer.from([255-buffer[0]]);
result += letter;
}
}
File.WriteAllText(outPath, result);
}
var inPath = "file.txt";
var outPath = "result.txt";
//Converted
using (var fdIn = new FileStream(inPath,FileMode.Open))
{
using (var fdOut = new FileStream(outPath, FileMode.OpenOrCreate))
{
var buffer = new byte[1];
var readCount = 0;
while (true)
{
readCount += fdIn.Read(buffer,0,1);
buffer[0] = (byte)(255 - buffer[0]);
fdOut.Write(buffer);
if (readCount == fdIn.Length)
break;
}
}
}
...
//Same code but all file loaded into memory, processed and after this saved
var input = File.ReadAllBytes(inPath);
for (int i = 0; i < input.Length; i++)
{
input[i] = (byte)(255 - input[i]);
}
File.WriteAllBytes(outPath, input);
Same code but with BinaryReader and BinaryWriter
var inPath = "file.txt";
var outPath = "result.txt";
using (BinaryReader fileIn = new BinaryReader(new StreamReader(#inPath).BaseStream))
using (BinaryWriter fileOut = new BinaryWriter(new StreamWriter(#outPath).BaseStream))
{
while (fileIn.BaseStream.Position != fileIn.BaseStream.Length)
{
var #byte = fileIn.ReadByte();
fileOut.Write((byte)(255 - #byte));
}
}
I'm trying to copy the contents of one Excel file to another Excel file while replacing a string inside of the file on the copy. It's working for the most part, but the file is losing 27 kb of data. Any suggestions?
public void ReplaceString(string what, string with, string path) {
List < string > doneContents = new List < string > ();
List < string > doneNames = new List < string > ();
using(ZipArchive archive = ZipFile.Open(_path, ZipArchiveMode.Read)) {
int count = archive.Entries.Count;
for (int i = 0; i < count; i++) {
ZipArchiveEntry entry = archive.Entries[i];
using(var entryStream = entry.Open())
using(StreamReader reader = new StreamReader(entryStream)) {
string txt = reader.ReadToEnd();
if (txt.Contains(what)) {
txt = txt.Replace(what, with);
}
doneContents.Add(txt);
string name = entry.FullName;
doneNames.Add(name);
}
}
}
using(MemoryStream zipStream = new MemoryStream()) {
using(ZipArchive newArchive = new ZipArchive(zipStream, ZipArchiveMode.Create, true, Encoding.UTF8)) {
for (int i = 0; i < doneContents.Count; i++) {
int spot = i;
ZipArchiveEntry entry = newArchive.CreateEntry(doneNames[spot]);
using(var entryStream = entry.Open())
using(var sw = new StreamWriter(entryStream)) {
sw.Write(doneContents[spot]);
}
}
}
using(var fileStream = new FileStream(path, FileMode.Create)) {
zipStream.Seek(0, SeekOrigin.Begin);
zipStream.CopyTo(fileStream);
}
}
}
I've used Microsoft's DocumentFormat.OpenXML and Excel Interop, however, they are both lacking in a few main components that I need.
Update:
using(var fileStream = new FileStream(path, FileMode.Create)) {
var wrapper = new StreamWriter(fileStream);
wrapper.AutoFlush = true;
zipStream.Seek(0, SeekOrigin.Begin);
zipStream.CopyTo(wrapper.BaseStream);
wrapper.Flush();
wrapper.Close();
}
Try the process without changing the string and see if the file size is the same. If so then it would seem that your copy is working correctly, however as Marc B suggested, with compression, even a small change can result in a larger change in the overall size.
I'm working on a project to transfer files between two COM ports.
First , I'm taking file name and extension and size before I convert the file to a byte array and send it to the second COM.
the problem is that I get strange characters in the beginning of the first readline method where I'm sending file name, like this :
"\0R\0\0\0\0\0\b\0\0\0S\0BAlpha" // file name
".docx" // file extension
"11360" // file size
here is the code I'm using to send the files :
Send sfile = new Send();
string path = System.IO.Path.GetFullPath(op.FileName);
sfile.Bytes = File.ReadAllBytes(path);
int size = sfile.Bytes.Length;
sfile.FileName = System.IO.Path.GetFileNameWithoutExtension(path);
sfile.Extension = System.IO.Path.GetExtension(path);
FileStream fs = new FileStream(path,FileMode.Open);
BinaryReaderbr = new BinaryReader(fs);
serialPort1.WriteLine(sfile.FileName); // sending file name
serialPort1.WriteLine(sfile.Extension);// sending extension
serialPort1.WriteLine(size.ToString());// sending size
byte[] b1 = br.ReadBytes((int)fs.Length);
for (int i = 0; i <= b1.Length; i++)
{
serialPort1.Write(b1, 0, b1.Length);
}
br.Close();
fs.Dispose();
fs.Close();
serialPort1.Close();
and the code below is used to receive data being sent :
string path1 = serialPort1.ReadLine();
string path2 = serialPort1.ReadLine();
string path3 = serialPort1.ReadLine();
int size = Convert.ToInt32(path3);
string path0 = #"C:\";
string fullPath = path0 + path1 + path2;
// File.Create(fullPath);
FileStream fs = new FileStream(fullPath, FileMode.Create);
byte[] b1 = new byte[size];
for (int i = 0; i < b1.Length; i++)
{
serialPort1.Read(b1, 0, b1.Length);
}
fs.Write(b1, 0, b1.Length);
fs.Close();
serialPort1.Close();
You are not writing the bytes correctly. It should be:
byte[] b1 = br.ReadBytes((int)fs.Length);
serialPort1.Write(b1, 0, b1.Length);
The way you read them is completely wrong as well. It should be:
byte[] b1 = new byte[size];
for (int i = 0; i < b1.Length; )
{
i += serialPort1.Read(b1, i, b1.Length - i);
}
I have a function that creates a zip file a string array of files passed. The function does succeed in creating the zip file and the zip entry files inside it, but these zip entry files are empty. I've tried a couple of different methods - the function code below is the closest I've gotten to something working:
public static bool ZipFile(string[] arrFiles, string sZipToDirectory, string sZipFileName)
{
if (Directory.Exists(sZipToDirectory))
{
FileStream fNewZipFileStream;
ZipOutputStream zos;
try {
fNewZipFileStream = File.Create(sZipToDirectory + sZipFileName);
zos = new ZipOutputStream(fNewZipFileStream);
for (int i = 0; i < arrFiles.Length; i++) {
ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));
zos.PutNextEntry(entry);
FileStream fStream = File.OpenRead(arrFiles[i]);
BufferedStream bfStrm = new BufferedStream(fStream);
byte[] buffer = new byte[bfStrm.Length];
int count;
while ((count = bfStrm.Read(buffer, 0, 1024)) != -1) {
zos.Write(buffer);
}
bfStrm.Close();
fStream.Close();
zos.CloseEntry();
}
zos.Close();
fNewZipFileStream.Close();
return true;
}
catch (Exception ex)
{
string sErr = ex.Message;
return false;
}
finally
{
fNewZipFileStream = null;
zos = null;
}
}
else
{
return false;
}
}
I think it's got to do with the byte stream handling. I've tried this bit of code that handles the stream but it goes into an infinite loop:
while ((count = fStream.Read(buffer, 0, 1024)) != -1) {
zos.Write(buffer, 0, count);
}
fStream.Close();
I found a solution that is quite simple - I used the ReadAllBytes method of the static File class.
ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));
zos.PutNextEntry(entry);
byte[] fileContents = File.ReadAllBytes(arrFiles[i]);
zos.Write(fileContents);
zos.CloseEntry();
Using Read() on a FileStream returns the amount of bytes read into the stream or 0 if the end of the stream has been reached. It will never return a value of -1.
From MSDN:
The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, orzero if the end of the stream is reached.
I'd modify your code to the following:
System.IO.FileStream fos = new System.IO.FileStream(sZipToDirectory + sZipFileName, FileMode.Create);
Java.Util.Zip.ZipOutputStream zos = new Java.Util.Zip.ZipOutputStream(fos);
byte[] buffer = new byte[1024];
for (int i = 0; i < arrFiles.Length; i++) {
FileInfo fi = new FileInfo (arrFiles[i]);
Java.IO.FileInputStream fis = new Java.IO.FileInputStream(fi.FullName);
ZipEntry entry = new ZipEntry(arrFiles[i].Substring(arrFiles[i].LastIndexOf("/") + 1));
zos.PutNextEntry(entry);
int count = 0;
while ((count = fis.Read(buffer)) > 0) {
zos.Write(buffer, 0, count);
}
fis.Close();
zos.CloseEntry();
}
This is nearly identical to the code I've used for creating zip archives on Android in the past.
Are you allowed to use SharpZip? It's really easy to use.
Here is a blog post I wrote to extract zip files
private static void upzip(string url)
{
WebClient wc = new WebClient();
wc.DownloadFile(url, "temp.zip");
//unzip
ZipFile zf = null;
try
{
zf = new ZipFile(File.OpenRead("temp.zip"));
foreach (ZipEntry zipEntry in zf)
{
string fileName = zipEntry.Name;
byte[] buffer = new byte[4096];
Stream zipStream = zf.GetInputStream(zipEntry);
using (FileStream streamWriter = File.Create( fileName))
{
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
}
finally
{
if (zf != null)
{
zf.IsStreamOwner = true;
zf.Close();
}
}
}
private void ZipFolder(string[] _files, string zipFileName)
{
using var memoryStream = new MemoryStream();
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var item in _files)
{
var demoFile = archive.CreateEntry(Path.GetFileName(item));
using var readStreamW = File.OpenRead(item);
using (var entryStream = demoFile.Open())
{
using (var streamWriter = new StreamWriter(entryStream))
{
readStreamW.Seek(0, SeekOrigin.Begin);
readStreamW.CopyTo(streamWriter.BaseStream);
}
}
}
}
using var fileStream = new FileStream(zipFileName, FileMode.Create);
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}
I wrote a program that split txt files into smaller pieces
But my problem is that my method is slow
Because this file size is 1gb and I use a variable named "pagesize" which base on that amount of lines in splitted files will be calculated
The problem is that the foreach is slow?
Is there a better way?
private void button1_Click(object sender, EventArgs e)
{
string inputFile = #"G:\Programming\C#\c# tamrin reza\large-Orders.txt";
int seed = 1000;
const int pageSize = 5000;
int count = 1;
const string destinationFileName = #"F:\Output\";
string outputFile;
string baseName = "-CustomerApp";
string extension = Path.GetExtension(inputFile);
var lst = new List<string>();
//FileInfo fileInfo = new FileInfo(inputFile);
//long fileSize = fileInfo.Length / pageSize;
FileStream fs = new FileStream(inputFile, FileMode.Open);
StreamReader sr = new StreamReader(fs);
while (!sr.EndOfStream)
{
for (int j = 1; j <= pageSize; j++)
{
var line = sr.ReadLine();
lst.Add(line);
}
outputFile = destinationFileName + count + baseName + extension;
CopyLines(lst, outputFile);
lst.Clear();
count++;
}
}
private void CopyLines(List<string> line, string outputFile)
{
FileStream outputFileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
//StreamWriter writer = new StreamWriter(outputFile);
//for (int i = 1; i < line.Count; i++)
//{
//}
using (StreamWriter sw = new StreamWriter(outputFileStream))
{
foreach (var li in line)
{
sw.WriteLine(li);
}
}
}
Thanks
You are iterating over the entire collection twice. If you write to the output file while you are reading, that will save one iteration over the entire collection.
while (!sr.EndOfStream)
{
outputFile = destinationFileName + count + baseName + extension;
FileStream outputFileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
using (StreamWriter sw = new StreamWriter(outputFileStream))
{
for (int j = 1; j <= pageSize; j++)
{
var line = sr.ReadLine();
sw.WriteLine(li);
}
}
lst.Clear();
count++;
}