I have problem with small thing...i coding auto updater and when i downloading .exe file i want to place it to main dir..and others .extension to sub dir.
File.exe = Here is i download place to main dir
Else = place to sub dir...but it isnt working, place all to main dir
if(ex[1] == "File.exe")
{
if (File.Exists(path))
{
if(File.Exists(String.Format("{0}WoW.exe", wow.GetValue("InstallPath").ToString())))
{
File.Copy(String.Format("{0}WoW.exe", wow.GetValue("InstallPath").ToString()), String.Format("{0}WoW_zaloha_Awrodar_old_file.exe", wow.GetValue("InstallPath").ToString()), false);
File.Delete(String.Format("{0}WoW.exe", wow.GetValue("InstallPath").ToString()));
}
else if(File.Exists(String.Format("{0}Wow.exe", wow.GetValue("InstallPath").ToString())))
{
File.Copy(String.Format("{0}Wow.exe", wow.GetValue("InstallPath").ToString()), String.Format("{0}Wow_zaloha_Awrodar_old_file.exe", wow.GetValue("InstallPath").ToString()), false);
File.Delete(String.Format("{0}Wow.exe", wow.GetValue("InstallPath").ToString()));
}
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(fs);
fs.Close();
StringBuilder sb = new StringBuilder();
foreach(byte b in retVal)
sb.Append(string.Format("{0:X2}", b));
if(ex[2] == sb.ToString())
proceed = false;
}
}
else
{
if(File.Exists(MPQpath))
{
FileStream fs = new FileStream(MPQpath, FileMode.Open, FileAccess.Read, FileShare.Read);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(fs);
fs.Close();
StringBuilder sb = new StringBuilder();
foreach(byte b in retVal)
sb.Append(string.Format("{0:X2}", b));
if(ex[2] == sb.ToString())
proceed = false;
}
}
Use Path.Combine for path manipulation to ensure correctness of filenames. Other than that I don't know what is wrong with your code. Have you traced it though to find out which line is causing your problem.
Related
I just want to copy a file to another location. But with a FileDialog.
I tried the code below but this is not working as I want...
Is there any other solution ?
SaveFileDialog saveFile = new SaveFileDialog();
if (saveFile.ShowDialog() == DialogResult.OK)
{
string newDirectory = saveFile.FileName;
System.IO.File.Copy(Path, newDirectory);
}
EDIT :
I want something like this :
Word exemple
A Filedialog with the default name of my source file and the right type. You can see an example when you try to save a Word.
Use the FileStream class . Which is more flexible, especially if you want to track the data transfer process byte by byte.
SaveFileDialog saveFile = new SaveFileDialog();
if (saveFile.ShowDialog() == DialogResult.OK)
{
string newDirectory = saveFile.FileName;
byte[] buffer = new byte[1024 * 1024];
int currentBlockSize = 0;
using (source = new FileStream(Path, FileMode.Open, FileAccess.Read))
{
using (dest = new FileStream(newDirectory, FileMode.CreateNew, FileAccess.Write))
{
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, currentBlockSize);
}
}
}
}
I have an interesting deli ma on my hands. I have created a program that takes 1-∞ zipped files that also contain X amount of individual files. The files in different folders sometimes get the same file name for whatever reason. This is my code that I have so far...
What this piece of code does is that after the object that is instantiated another object calls this function called unzip(). what all failsafe.check_directory() just makes sure that the temporary folder were all the going to be unzipped files are going to go in is empty. the first try catch is for anything I do not know about yet, but the second try catch is for catching duplicate duplicate files so when it actually does happen... the program will not break. So the question I am Asking is what is the best way to handle this exception without just kicking the duplicate to the side or in other words, is there to rename that file before its to late.
public bool unzip()
{
int bad_file = 0;
failsafe.check_directory();
string dupes = "dupe files\r\n";
try
{
for (int i = 0; i < zippedfolders.Length; i++)
{
try
{
bad_file = i;
ZipFile.ExtractToDirectory(zippedfolders[i], temppath);
}
catch
{
dupes += zippedfolders[bad_file]+"\r\n";
continue;
}
}
File.WriteAllText(#"C:\MDSSCRUBBER\BUGGED_FILE.txt", dupes);
files = Directory.GetFiles(temppath);
return true;
}
catch
{
return false;
}
}
This is how I handled it... For some odd reason the Directory class is not creating a folder in the Desktop.
private void fix_desktop()
{
string pathington = Environment.SpecialFolder.Desktop + #"\MrEncrypto\";
bool check = !Directory.Exists(pathington);
string finaloutput = Environment.SpecialFolder.Desktop + #"\MrEncrypto\";
if (!check)
{
Directory.CreateDirectory(pathington);
}
else
{
foreach (string file in Directory.GetFiles(Environment.SpecialFolder.Desktop + #"\MrEncrypto"))
{
File.Delete(file);
}
}
foreach (string file in files)
{
try
{
FileStream fsInput = new FileStream(file, FileMode.Open, FileAccess.Read);
FileStream fsencrypt = new FileStream(finaloutput + Path.GetFileName(file), FileMode.Create, FileAccess.Write);
/** DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
DES.IV = ASCIIEncoding.ASCII.GetBytes(IV);**/
AesCryptoServiceProvider DES = new AesCryptoServiceProvider();
DES.BlockSize = 128;
DES.KeySize = 256;
DES.IV = ASCIIEncoding.ASCII.GetBytes(IV);
DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
DES.Padding = PaddingMode.PKCS7;
DES.Mode = CipherMode.CBC;
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream ocstream = new CryptoStream(fsencrypt, desencrypt, CryptoStreamMode.Write);
//reading time
byte[] filetobyte = new byte[fsInput.Length - 1];
fsInput.Read(filetobyte, 0, filetobyte.Length);
ocstream.Write(filetobyte, 0, filetobyte.Length);
fsInput.Close();
ocstream.Close();
fsencrypt.Close();
}
catch
{
continue;
}
}//foreach
SystemSounds.Beep.Play();
Encrypto.Enabled = false;
}//function
I need to create a StreamWriter from a FileStream object and append some text to
the file. It is assumed that the FileStream object that is being used has been created with FileMode.OpenOrCreate and FileAccess.ReadWrite. I have:
using (FileStream fs = GetCurrentFileStream())
{
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("StringToAppend");
sw.Flush();
}
However this just overwrites the file from the beginning. How do I move to the end of the file? Is there perhaps a way to change the FileMode to Append and FileAccess to Write after the FileStream has been created?
Edit: As mentioned above I need to do this using a FileStream object. The answers from Open existing file, append a single line assume that I can create a new StreamWriter from the file path which I don't have.
Edit 2: Added truncated version of GetCurrentFileStream().
public static FileStream GetCurrentFileStream()
{
String fileName = getFileName();
FileStream fs = OpenFileWhenAvailable(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
public static FileStream OpenFileWhenAvailable(String fileName, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
{
int tries = 0;
int timeout = 10 * 1000;
while (true)
{
tries++;
try
{
return new FileStream(fileName, fileMode, fileAccess, fileShare);
}
catch (IOException ex)
{
if (tries * 100 > timeout)
{
return null;
}
else
{
System.Threading.Thread.Sleep(100);
}
}
}
}
GetCurrentFileStream is used in several different contexts, so changing the FileMode and FileAccess directly is not an option. I do not wish to make a separate version of GetCurrentFileStream just for this one case, which is why I'm asking if there is a way to jump to the end of the stream and append a string when the FileStream object has already been created.
If I understood correctly, you want to append your line to a created file:
using (FileStream fs = GetCurrentFileStream())
{
StreamWriter sw = new StreamWriter(fs, true);
sw.WriteLine("StringToAppend");
sw.Flush();
}
With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it.
It will be really cool if you show your implementation of method GetCurrentStream():
using (FileStream fileStream = new FileStream(fileName,FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(something);
}
Update:
using (FileStream fs = GetCurrentFileStream())
{
StreamWriter sw = new StreamWriter(fs);
long endPoint=fs.Length;
// Set the stream position to the end of the file.
fs.Seek(endPoint, SeekOrigin.Begin);
sw.WriteLine("StringToAppend");
sw.Flush();
}
If you really really wanted to, you could pretty this up....
static int iMaxLogLength = 15000;
static int iTrimmedLogLength = -2000;
static public void writeToFile2(string strMessage, string strLogFileDirectory, int iLogLevel)
{
string strFile = strLogFileDirectory + "log.log";
try
{
FileInfo fi = new FileInfo(strFile);
Byte[] bytesRead = null;
if (fi.Length > iMaxLogLength)
{
using (BinaryReader br = new BinaryReader(File.Open(strFile, FileMode.Open)))
{
// Go to the end of the file and backup some
br.BaseStream.Seek(iTrimmedLogLength, SeekOrigin.End);
// Read that.
bytesRead = br.ReadBytes((-1 * iTrimmedLogLength));
}
}
byte[] newLine = System.Text.ASCIIEncoding.ASCII.GetBytes(Environment.NewLine);
FileStream fs = null;
if (fi.Length < iMaxLogLength)
fs = new FileStream(strFile, FileMode.Append, FileAccess.Write, FileShare.Read);
else
fs = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.Read);
using (fs)
{
if (bytesRead != null)
{
fs.Write(bytesRead, 0, bytesRead.Length);
fs.Write(newLine, 0, newLine.Length);
Byte[] lineBreak = Encoding.ASCII.GetBytes("### " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " *** *** *** New Log Start Position *** *** *** *** ###");
fs.Write(lineBreak, 0, lineBreak.Length);
fs.Write(newLine, 0, newLine.Length);
}
Byte[] sendBytes = Encoding.ASCII.GetBytes(strMessage);
fs.Write(sendBytes, 0, sendBytes.Length);
fs.Write(newLine, 0, newLine.Length);
}
}
catch (Exception ex)
{
; // Write to event or something
}
}
I have an image in ushort variable, want to save this image in binary format.
Please, anyone, tell me How can this be done using C#?
I have tried this but its not working
ushort[] Depthdata;
Depthdata = new ushort[DWidth * DHeight];
string s1 = string.Format("{0}", count_depth);
FileStream fs = new FileStream("C:\\img" + s1 + ".bin", FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
string image_str = Convert.ToString(Imagedata);
bw.Write(image_str);
bw.Close();
fs.Close();
Here is attached my full code
I would like to mention that the code here, and the one in your link are different...
In any case, going by the one in your link:
ushort[] Depthdata;
....
string s1 = string.Format("{0}", count_depth);
FileStream fs = new FileStream("G:\\test" + s1 + ".bin", FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
string depth_str = Convert.ToString(Depthdata);
bw.Write(depth_str);
bw.Close();
fs.Close();
You shouldn't actually need to convert your Depthdata to a string. BinaryWriter can actually take a ushort value in one of its overloads. Why not just iterate through and write it out? Also, you should use using statements for your filestream and binarywriter.
Try the following:
using(FileStream fs = new FileStream("G:\\test" + s1 + ".bin", FileMode.Create, FileAccess.Write))
{
using(BinaryWriter bw = new BinaryWriter(fs))
{
foreach(ushort value in Depthdata)
{
bw.write(value);
}
}
}
I think this will help you.i tested this on *.tiff file
first make separate Class Ext
public static class Ext
{
public static string ToHexString(this byte[] hex)
{
if (hex == null) return null;
if (hex.Length == 0) return string.Empty;
var s = new StringBuilder();
foreach (byte b in hex)
{
s.Append(b.ToString("x2"));
}
return s.ToString().ToUpper();
}
}
then you can Add following code to convert image to string binary
FileStream fs=new FileStream(ImgPathID, FileMode.Open, FileAccess.Read); //set file stream
Byte[] bindata=new byte[Convert.ToInt32(fs.Length)];
fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
string bindatastring = Ext.ToHexString(bindata);// call to class
I am using ICSharpCode.SharpZipLib.Zip.FastZip to zip files but I'm stuck on a problem:
When I try to zip a file with special characters in its file name, it does not work. It works when there are no special characters in the file name.
I think you cannot use FastZip. You need to iterate the files and add the entries yourself specifying:
entry.IsUnicodeText = true;
To tell SharpZipLib the entry is unicode.
string[] filenames = Directory.GetFiles(sTargetFolderPath);
// Zip up the files - From SharpZipLib Demo Code
using (ZipOutputStream s = new
ZipOutputStream(File.Create("MyZipFile.zip")))
{
s.SetLevel(9); // 0-9, 9 being the highest compression
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
entry.IsUnicodeText = true;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
s.Finish();
s.Close();
}
You can continue using FastZip if you would like, but you need to give it a ZipEntryFactory that creates ZipEntrys with IsUnicodeText = true.
var zfe = new ZipEntryFactory { IsUnicodeText = true };
var fz = new FastZip { EntryFactory = zfe };
fz.CreateZip("out.zip", "C:\in", true, null);
You have to download and compile the latest version of SharpZipLib library so you can use
entry.IsUnicodeText = true;
here is your snippet (slightly modified):
FileInfo file = new FileInfo("input.ext");
using(var sw = new FileStream("output.zip", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using(var zipStream = new ZipOutputStream(sw))
{
var entry = new ZipEntry(file.Name);
entry.IsUnicodeText = true;
zipStream.PutNextEntry(entry);
using (var reader = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
byte[] actual = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, actual, 0, bytesRead);
zipStream.Write(actual, 0, actual.Length);
}
}
}
}
Possibility 1: you are passing a filename to the regex file filter.
Possibility 2: those characters are not allowed in zip files (or at least SharpZipLib thinks so)
try to take out the special character from the file name, i,e replace it.
your Filename.Replace("&", "&");