I am transfering files through sockets. When I try to save files to a custom directory, I get this error using BinaryWrite function.
private void downloadFromServer()
{
try
{
byte[] buffer = new byte[5000 * 1024];
byte[] incomingFile = new byte[5000 * 1024];
buffer = Encoding.Default.GetBytes(getUserName.Text + "Download"
+ getFileName.Text + "end");
clientSocket.Send(buffer);
activityLog.AppendText("Preparing to download... \n");
while (incomingFile != null)
{
clientSocket.Receive(incomingFile);
int receivedBytesLen = incomingFile.Length;
int fileNameLen = BitConverter.ToInt32(incomingFile, 0);
File.WriteAllBytes(fileDir, incomingFile);
}
activityLog.AppendText("File saved to " + fileDir + "\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
File.WriteAllBytes(fileDir, incomingFile); requires file name. From variable name it looks like you are using folder name. I.e. should be #"e:\tempfile.bin" instead of #"e:\".
File.WriteAllBytes
Given a byte array and a file path, this method opens the specified file, writes the contents of the byte array to the file, and then closes the file.
Note if fileDir means file name than you should looks for other not-so-truthful names throughout your code...
Related
I'm currently working on a project that include file transferring. The way I originally planned it was to read it in python via
f = open(filename)
f.read()
and write it in C# using the File object interface, and the same from C#, I'm reading it through
File.ReadAllText(file)
and saving it in python.
It is transferred via sockets.
For some reason, it keeps corrupting the files. Even though the sending is perfectly fine(I checked it a thousand times), the files is read and written properly, so I'm looking for information about how to read a file through text(only text) and not having it corrupted. Any help is welcome, thanks.
Networking(Python):
def send(msg, sock):
msg = msg.__repr__()
size_of_package = sys.getsizeof(msg)
package = str(size_of_package)+":"+ msg
sock.send(package)
def recv(sock):
try:
header = sock.recv(2)
while ":" not in header:
header += sock.recv(2)
size_of_package, separator, message_fragment = header.partition(":")
message = ""
while len(message) < int(size_of_package) - len(message_fragment):
recvsize = int(size_of_package) - len(message_fragment) - len(message)
if recvsize > 2048:
recvsize = 2048
message+=sock.recv(recvsize)
full_message = message_fragment + message
return full_message
except OverflowError:
return "OverflowError."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
Networking C#:
private void Send(string st)
{
int size = Encoding.ASCII.GetByteCount(st);
string pack = size + ":" + st;
buffer = Encoding.ASCII.GetBytes(pack);
connection.Send(buffer);
MessageBox.Show(buffer.Length.ToString());
}
private string Recv()
{
try
{
buffer = new byte[2];
connection.Receive(buffer, 2, SocketFlags.Partial);
string header = Encoding.ASCII.GetString(buffer, 0, 2);
while (!header.Contains(":"))
{
connection.Receive(buffer, 2, SocketFlags.Partial);
header += Encoding.ASCII.GetString(buffer, 0, 2);
}
int size = int.Parse(header.Split(':')[0]);
string mes0 = header.Split(':')[1];
buffer = new byte[size];
connection.Receive(buffer, size, SocketFlags.Partial);
string fullmes = mes0 + Encoding.ASCII.GetString(buffer);
return fullmes;
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
return "";
}
File saving (Python)
class fileSaver:
def __init__(self , fileInf):
self.fileInf = fileInf
self.file = open(BASE_PATH+fileInf.getPath(), "wb")
self.file.write(fileInf.getContent())
self.file.close()
where fileInf is an object that contains all the info, including content, etc.
File loading(C#):
StreamReader sr = new StreamReader(file);
networking.Upload(file.Substring(file.LastIndexOf('/')+1), basepath, sr.ReadToEnd());
sr.Close();
I have a page where the User can either upload their own csv or enter values into a listbox which then creates a csv (in the background). Regardless of which way the csv gets created I need to upload that csv to our server via a byte stream.
My problem is that when Im creating the csv I shouldn't have to create a temporary file, I should be able to write to the stream then read it back for uploading. How can I remove the need for the temporary file?
current code which works (but uses temp file):
try {
string filename = DateTime.Now.ToString("MMddyyHmssf");
filename = filename + ".csv";
string directory = ConfigurationManager.AppSettings["TempDirectory"].ToString();
path = Path.Combine(directory, filename);
using (StreamWriter sw = File.CreateText(path)) {
foreach (ListItem item in this.lstAddEmailAddress.Items) {
sw.WriteLine(" , ," + item.ToString());
}
}
} catch (Exception ex) {
string error = "Cannot create temp csv file used for importing users by email address. Filepath: " + path + ". FileException: " + ex.ToString();
this.writeToLogs(error, 1338);
}
}
// put here for testing the byte array being sent vs ready byte[] byteArray = System.IO.File.ReadAllBytes(path);
myCsvFileStream = File.OpenRead(path);
nFileLen = (int)myCsvFileStream.Length;
I have tried
Stream myCsvFileStream;
using (StreamWriter sw = new StreamWriter(myCsvFileStream)) {
foreach (ListItem item in this.lstAddEmailAddress.Items) {
sw.WriteLine(" , ," + item.ToString());
}
}
However since myCsvFileStream is not initialized (because stream is a static class) it is always null.
Here is what I do with the data (byte stream) after creating the csv.
byte[] file = new byte[nFileLen];
myCsvFileStream.Read(file, 0, nFileLen);
bool response = this.repositoryService.SaveUsers(this.SelectedAccount.Id, file, this.authenticatedUser.SessionToken.SessionId);
myCsvFileStream.Close();
In the end I used StringBuilder to create my csv file contents. Then got a byte array of its contents and used that to populate my shared stream (I say shared because when the user enters their own CSV file it is a HttpPostedFile but when sending it to our server via the rest call (respositoryservices.saveusers) it uses the same byte stream that it would via this method)
StringBuilder csvFileString = new StringBuilder();
sharedStreamForBatchImport = new MemoryStream();
foreach (ListItem item in this.lstAddEmailAddress.Items) {
csvFileString.Append(",," + item.ToString() + "\\r\\n");
}
//get byte array of the string
byteArrayToBeSent = Encoding.ASCII.GetBytes(csvFileString.ToString());
//set length for read
byteArraySize = (int)csvFileString.Length;
//read bytes into the sharedStreamForBatchImport (byte array)
sharedStreamForBatchImport.Read(byteArrayToBeSent, 0, byteArraySize);
You want to create a new MemoryStream()
Here is a function I use to write CSV files
public static bool WriteCsvFile(string path, StringBuilder stringToWrite)
{
try
{
using (StreamWriter sw = new StreamWriter(path, false)) //false in ordre to overwrite the file if it already exists
{
sw.Write(stringToWrite);
return true;
}
}
catch (Exception)
{
return false;
}
}
stringToWrite is just a string that has been created that way :
public static bool WriteCsvFile(string path, DataTable myData)
{
if (myData == null)
return false;
//Information about the table we read
int nbRows = myData.Rows.Count;
int nbCol = myData.Columns.Count;
StringBuilder stringToWrite = new StringBuilder();
//We get the headers of the table
stringToWrite.Append(myData.Columns[0].ToString());
for (int i = 1; i < nbCol; ++i)
{
stringToWrite.Append(",");
stringToWrite.Append(myData.Columns[i].ToString());
}
stringToWrite.AppendLine();
//We read the rest of the table
for (int i = 0; i < nbRows; ++i)
{
stringToWrite.Append(myData.Rows[i][0].ToString());
for (int j = 1; j < nbCol; ++j)
{
stringToWrite.Append(",");
stringToWrite.Append(myData.Rows[i][j].ToString());
}
stringToWrite.AppendLine();
}
return WriteCsvFile(path, stringToWrite);
}
I am facing a issue in my code. PFA my code below
// Extract Zip File
public static void Extract(string zipFileName, string destinationPath)
{
ZipFile zipfile = new ZipFile(zipFileName);
List<ZipEntry> zipFiles= GetZipFiles(zipfile);
foreach (ZipEntry zipFile in zipFiles)
{
if (!zipFile.isDirectory())
{
java.io.InputStream s=zipfile.getInputStream(zipFile);
//InputStream s = zipfile.getInputStream(zipFile);
try
{
Directory.CreateDirectory(destinationPath + "\\" + Path.GetDirectoryName(zipFile.getName()));
// Directory.CreateDirectory(destinationPath + "\ + Path.GetDirectoryName(zipFile.getName()));
//Directory.CreateDirectory(Path.GetDirectoryName(zipFile.getName()));
java.io.FileOutputStream dest = new java.io.FileOutputStream(Path.Combine(destinationPath + "\\" + Path.GetDirectoryName(zipFile.getName()),
//java.io.FileOutputStream dest = new java.io.FileOutputStream(Path.Combine(Path.GetDirectoryName(zipFile.getName()),
Path.GetFileName(zipFile.getName())));
try
{
int len = 0;
byte[] buffer = new byte[7168];
while ((len = s.read(buffer)) >= 0)
{
dest.write(buffer, 0, len);
}
}
finally
{
dest.close();
}
}
finally
{
s.close();
}
}
}
}
Issue is : In this class can any one tell me formatof "string zipFileName, string destinationPath " means : which pathformate be use in zipFileName and designationPath.
This code is used for Unzip file using J# in c# please help me as soon as possible
: here zipFilename is path file to be ziped and destinationPath is path where file to be unzipped.
If I understand your question correctly, and you're working on Windows, then you would probably use a format like:
Extract(#"c:\myfolder\mysubfolder\myfile.zip", #"c:\mydestinationfolder\mysubfolder");
Give it a try and leave a comment to let me know if it works, or whatever else you've tried previously.
Are you using any compression libraries . For example the ZipFile - Is this any third party library ?
You can check compression libraries for C# that are available incase you plan to implement it.
I am using the library ICSharpCode.SharpZipLib.Zip;
My code is follows:
The path is root. \\ALAWP\\THIS\\ACORD\\
I'm zipping them to the ZIPDirectory
However when it's done the file is not named acord_combined.txt, instead it's called ACORD\acord_combined.txt
What am I doing wrong?
public void CleanRoot()
{
DirectoryInfo RootDi = new DirectoryInfo(FilePrep.RootDirectory);
string ZipDirectory = FilePrep.RootDirectory + "\\processed\\AceKey"+ DateTime.Now.ToString("yyyyMMdd_H;mm;ss") +".zip";
ZipOutputStream NewZipOutput = new ZipOutputStream(File.Create(ZipDirectory));
foreach (FileInfo fi in RootDi.GetFiles("acord*.*"))
{
Compress(ref NewZipOutput, fi);
//MoveFile(fi.FullName,ZipDirectory);
}
NewZipOutput.Finish();
NewZipOutput.Close();
}
public void Compress(ref ZipOutputStream ZipFolder, FileInfo fi)
{
try
{
FileStream fsFileToBeZipped = fi.OpenRead();
ZipEntry entry = new ZipEntry(fi.FullName);
ZipFolder.PutNextEntry(entry);
int size = 2048;
byte[] buffer = new byte[size];
while (true)
{
size = fsFileToBeZipped.Read(buffer, 0, buffer.Length);
if (size > 0)
ZipFolder.Write(buffer, 0, size);
else
break;
} //end while ( true )
fsFileToBeZipped.Close();
//prepare and delete file
fi.Attributes = FileAttributes.Normal;
//fi.Delete();
} //end try
catch (Exception e)
{
Console.WriteLine("Error zipping File. Error - " + e.Message);
} //end catch
}
Your problem is right here
new ZipEntry(fi.FullName);
The argument to zipEntry is the path in the zip file, not the full path the compressed data comes from. Usually zip libraries, such as 7zip and SharpZip, expose a way to create an "entry path" but the actual data written to the zip is from the full path.
Probably what you want is
new ZipEntry(Path.GetFileName(fi.fullName))
I want to convert a zip file to MSI file/EXE file/windows installation file to install in remote computers in the network.
Up to now, I can make a zip file with user selected executable files and related support files etc. using the following C# code.
private void btnPackaging_Click(object sender, EventArgs e)
{
// make sure there are files to zip
if (listBox1.Items.Count < 1)
{
MessageBox.Show("There are no files queued for the zip operation", "Empty File Set");
return;
}
// make sure there is a destination defined
if (textBox1.Text == string.Empty)
{
MessageBox.Show("No destination file has been defined.", "Save To Empty");
return;
}
label3.Visible = true;
label3.Refresh();
// name the zip file whatever the folder is named
// by splitting the file path to get the folder name
string[] sTemp = textBox1.Text.Split('\\');
string sZipFileName = sTemp[sTemp.Length - 1].ToString();
// check to see if zipped file already exists
// user may rename it in the text box if it does.
FileInfo fi = new FileInfo(textBox1.Text + "\\" + sZipFileName + ".zip");
if (fi.Exists)
{
// move it to the folder
try
{
StringBuilder sb = new StringBuilder();
sb.Append("The file " + sZipFileName + " already exists. ");
sb.Append("You may rename it in the save to text box.");
MessageBox.Show(sb.ToString(), "Existing File Name");
textBox1.Focus();
return;
}
catch
{
MessageBox.Show("Rename the file or select a new location.", "File Error");
return;
}
}
// Check for the existence of the target folder and
// create it if it does not exist
if (!System.IO.Directory.Exists(textBox1.Text + "\\TempZipFile\\"))
{
System.IO.Directory.CreateDirectory(textBox1.Text + "\\TempZipFile\\");
}
// Set up a string to hold the path to the temp folder
string sTargetFolderPath = (textBox1.Text + "\\TempZipFile\\");
// Process the files and move each into the target folder
for (int i = 0; i < listBox1.Items.Count; i++)
{
string filePath = listBox1.Items[i].ToString();
FileInfo fi2 = new FileInfo(filePath);
if (fi2.Exists)
{
// move it to the folder
try
{
fi2.CopyTo(sTargetFolderPath + fi2.Name, true);
}
catch
{
// clean up if the operation failed
System.IO.Directory.Delete(sTargetFolderPath);
MessageBox.Show("Could not copy files to temp folder.", "File Error");
return;
}
}
}
// zip up the files
try
{
label3.Visible = true;
label3.Refresh();
string[] filenames = Directory.GetFiles(sTargetFolderPath);
// Zip up the files - From SharpZipLib Demo Code
using (ZipOutputStream s = new ZipOutputStream(File.Create(textBox1.Text + "\\" + sZipFileName + ".zip")))
{
s.SetLevel(9); // 0-9, 9 being the highest level of compression
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
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();
}
// remove the progress bar
label3.Visible = false;
// clean up files by deleting the temp folder and its content
System.IO.Directory.Delete(textBox1.Text + "\\TempZipFile\\", true);
// Notify user
MessageBox.Show("Zip file " + textBox1.Text + " created.");
// empty everything
listBox1.Items.Clear();
textBox1.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Zip Operation Error");
}
this.Dispose();
}
I don't have any idea, how to develop C# code to convert zip file into MSI file/EXE file/windows installation file.
Please help me, if anybody have an idea to solve this.
Thanks in Advance.