unable to archive and unarchive files using 7zip in asp.net - c#

I have to do transfer files from one host to other so i have decided to go with zip (IONIC) but problem with that is it eat's lot of memory when it comes for larger file, so i have decided to go with 7Z dll. i had tried to achieve compress & Uncompress which works perfectly fine on my console after changing some settings (unchecked prefer-32 bit from https://blog.jongallant.com/2011/10/7-zip-dll-file-does-not-exist/).
but which fails on ASP.net application and i am getting "Can not load 7-zip library or internal COM error! Message: failed to load library." when i try to compress or uncompress.
the code what i have tried.
protected void btnCompress_Click(object sender, EventArgs e)
{
var dllPath = "";
if (Environment.Is64BitOperatingSystem)
{
dllPath = HttpContext.Current.Server.MapPath(#"7z\7z64.dll");
}
else
dllPath = HttpContext.Current.Server.MapPath(#"7z\7z.dll");
var tmpPath = System.IO.Path.Combine(txtTempPath.Text, txtDir.Text);
try
{
SevenZip.SevenZipCompressor.SetLibraryPath(dllPath);
SevenZipCompressor sz = new SevenZipCompressor();
sz.CompressionLevel = CompressionLevel.Ultra;
sz.CompressionMode = CompressionMode.Create;
sz.CompressionMethod = CompressionMethod.Default;
sz.FastCompression = true;
sz.CompressDirectory(tmpPath, tmpPath + "_7Zip.7z");
//Directory.Delete(backupFolder, true);
Response.Write("<script>alert('Compressed successfully');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
//throw ex;
}
}
protected void btnExtract_Click(object sender, EventArgs e)
{
try
{
var tmpPath = System.IO.Path.Combine(txtTempPath.Text, txt7z.Text);
SevenZipExtractor.SetLibraryPath(#"C:\Program Files\7-Zip\7z.dll");
SevenZipExtractor zip = new SevenZipExtractor(tmpPath);
zip.ExtractArchive(System.IO.Path.GetFileNameWithoutExtension(tmpPath));
Response.Write("<script>alert('Extracted successfully');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
please someone suggest a proper solution for this,
Thanks in Advance.

I think using (Environment.Is64BitProcess) instead of Environment.Is64BitOperatingSystem) will work if you have set correct dll path.Make sure that dll exists in that path.

Related

How to transfer the file from Windows Form Application to Xamarin Forms using USB cable C#.net

I am now developing Android Application and the Windows Form.
In the previous, the users need to plug in with USB, copy the file and paste into android folder but it would be troublesome and takes time to do.
How can I transfer the file directly from the PC to android Folder (Internal Storage/ downloads) ?
I tried with FolderBrowserDialog to browse and copy into android but "OK" button is disabled when I point the location. enter image description here
Should I write it in Windows Form backend or Xamarin Forms backend side in order to direct transfer into the Android App?
I cannot use Web API as cannot use the internet connection.
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
txtCopy.Text = dialog.SelectedPath;
}
string copyFileName = Path.Combine(txtCopy.Text, originalFile); //originalFile->FileName (testing.jpg)
File.Copy(txtFile1.Text, copyFileName, true);
Direct file transfer from Windows Form and Xamarin Forms by clicking button
I too had issues with copying to/from Android with Xamarin. Originally directed to use ADB.exe (Android Debug Bridge), but that had too many security holes / issues and was restricted from using that. Could not use generic 3rd party for other reasons and had to write my own Android / Xamarin file transfer library (works great). One thing I found in MY research was what was the naming convention for paths did not always match what you think it might / should. For example, your "Internal shared storage" wasn't really that when I connected.
"DT50\Internal shared storage\Download"
it was just
"Internal Storage\Download".
Did not have a leading \ character and it worked. Writing to other directories, you need to prompt/grant permission on the Xamarin side to look at SOME possible other working folder directories, but that might be something for you at another time.
Based on your code, I made a Windows Form project to complete the copy.
You could refer to the following code:
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dialog.SelectedPath;
}
}
private void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.ShowDialog();
textBox2.Text = dialog.SelectedPath;
}
private void button3_Click(object sender, EventArgs e)
{
DirectoryInfo thefolder = new DirectoryInfo(textBox1.Text);
foreach (FileInfo nextfile in thefolder.GetFiles())
{
try
{
string filename = nextfile.Name;
string filefullname = nextfile.FullName;
string mudi = textBox2.Text + "\\" + filename;
if (File.Exists(mudi))
{
//File.Delete(mudi);
}
else
{
File.Copy(filefullname, mudi);
MessageBox.Show("Successful");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
Now I got it. I have to download MediaDevices framework in NuGet Package Manager to download/ transfer the file from Android device to PC.
I can transfer the file from Android to PC.
But the thing is I cannot transfer/ Upload the file from PC to Android (when using PCToPDA()). When I run the program, the error Director "DT50\Internal shared storage\Download" not found appear even though the directory path is correct.
Any idea why is that happening?
Updated One
The problem has been solved. Instead of writing "DT50\Internal shared storage\Download", I have to remove DT50 and just "\Internal shared storage\Download". Commented the wrong one and Updated the correct the source code below.
string originalFile;
private void BtnBrowse_Click(object sender, EventArgs e)
{
Browse(); //Get the files from Android Folder
}
private void Browse()
{
try
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
txtFile1.Text = openFileDialog1.FileName;
string fileName = Path.GetDirectoryName(openFileDialog1.FileName);
originalFile = Path.GetFileName(openFileDialog1.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Browse-ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void BtnCopy_Click(object sender, EventArgs e)
{
PDAToPC(); //Android to PC
//PCToPDA(); //PC to Android
}
private void PDAToPC()
{
try
{
string DeviceNameAsSeenInMyComputer = "DT50";
var devices = MediaDevice.GetDevices();
using (var device = devices.Where(d => d.FriendlyName == DeviceNameAsSeenInMyComputer || d.Description == DeviceNameAsSeenInMyComputer).First())
{
device.Connect();
var photoDir = device.GetDirectoryInfo(#"\Internal shared storage\Download");
var files = photoDir.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
string destinationFileName = $#"D:\KhineThein\Testing\TransferTesting\photo\{file.Name}";
if (!File.Exists(destinationFileName))
{
using (FileStream fs = new FileStream(destinationFileName, FileMode.Create, System.IO.FileAccess.Write))
{
device.DownloadFile(file.FullName, fs);
}
}
}
device.Disconnect();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "PDAToPC-ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void PCToPDA()
{
try
{
string DeviceNameAsSeenInMyComputer = "DT50";
string tempFileName = "CaptureImport.txt";
var devices = MediaDevice.GetDevices();
using (var device = devices.Where(d => d.FriendlyName == DeviceNameAsSeenInMyComputer || d.Description == DeviceNameAsSeenInMyComputer).First())
{
device.Connect();
var photoDir = device.GetDirectoryInfo(#"\Internal shared storage\Download");
var files = photoDir.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly);
foreach (var file in files)
{
string originalFileName = $#"D:\KhineThein\Testing\TransferTesting\photo\{tempFileName}";
//string transferToFileName = $#"{DeviceNameAsSeenInMyComputer}\Internal shared storage\Download\{tempFileName}";
string transferToFileName = $#"\Internal shared storage\Download\{tempFileName}";
using (FileStream fs = new FileStream(originalFileName, FileMode.Open, System.IO.FileAccess.Read))
{
//device.DownloadFile(file.FullName, fs); //Path, Stream
device.UploadFile(fs, transferToFileName); //Stream, Path
}
}
device.Disconnect();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "PCToPDA-ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

What is a Win32 Exception the system cannot find the file specified

I have a problem with Process.Start(), i want it to open specified file when I double click on tree node.
This is my code where it should open file
String path = "C:\\Users\\........\\something";
private void treePrica_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
{
try {
String TreeNodeName = treePrica.SelectedNode.ToString().Replace("TreeNode: ", String.Empty);
MessageBox.Show(this.path + "\\" + TreeNodeName);
Process.Start(this.path + "\\" + TreeNodeName);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
When i double click on any of the nodes containing .txt file it throws exception like this
just use string path = #"c:/something"; and make sure you add the extension to the total path!

(WPF) Copying files "The file is open in another process"

I'm making a WPF C# Application and I need to copy a file. As the title says whenever I select any file it says its open in another process, so I'm guessing its something to do with my code.
I've attempted to rewrite the File.Copy code to be able to be able to track the progress of the copying.
My file copying code
public static void CopyFile(string file, string destination, ProgressBar progressCallback)
{
try
{
if (!Directory.Exists(destination)) Directory.CreateDirectory(destination);
} catch (IOException e)
{
MessageBox.Show("There was an error while creating the resource packs directory " + e.Message, "Canno't create directory", MessageBoxButton.OK);
return;
}
int halfAMeg = (int)(1024 * 1024 * 0.4);
FileStream strIn = null;
FileStream strOut = null;
try
{
strIn = new FileStream(file, FileMode.Open);
strOut = new FileStream(Path.Combine(destination, file), FileMode.Create);
}
catch (IOException e)
{
MessageBox.Show("There was an error while copying the file: " + e.Message, "Canno't copy file", MessageBoxButton.OK);
return;
}
byte[] buf = new byte[halfAMeg];
while (strIn.Position < strIn.Length)
{
int len = strIn.Read(buf, 0, buf.Length);
strOut.Write(buf, 0, len);
progressCallback.Maximum = Int32.MaxValue;
progressCallback.Value = (int)(Int32.MaxValue / (strIn.Position / strIn.Length));
}
strIn.Close();
strOut.Close();
}
Any help would be greatly appreciated.
EDIT 10/22: This question was made years ago when I greatly underestimated my C++ ability. I apologise for the poor code and poorly written question!

Cannot save song from isolated storage, SaveSong method throws InvalidOperationException error

I'm building a FTP application for Windows Phone 8, and want to save the downloaded songs from the isolated storage to the media library. I check if the file exists in isostore, and it returns true, but when I'm using the SaveSong method it always throws an exception. Here is the code sample:
private async void contextMenuItem1_Click(object sender, RoutedEventArgs e)
{
string fileName = (sender as MenuItem).DataContext.ToString();
MediaLibrary library = null;
......
else if (fileName.EndsWith(".mp3") || fileName.EndsWith(".wav") || fileName.EndsWith(".aac"))
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (myIsolatedStorage.FileExists(fileName))
{
library = new MediaLibrary();
StorageFile localFile = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
if (localFile != null)
{
//MessageBox.Show("StorageFile is: " + localFile.Name);
try
{
library.SaveSong(new Uri(localFile.Name, UriKind.RelativeOrAbsolute), null, SaveSongOperation.CopyToLibrary);
//MediaLibraryExtensions.SaveSong(media, new Uri(fileName, UriKind.RelativeOrAbsolute), null, SaveSongOperation.CopyToLibrary);
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Exception caught: " + ex.Message);
}
}
}
else
MessageBox.Show("File does not exist in isostore");
}
}
I wolud be very grateful if anybody could help me, thx.
If your file name or file path is null then this exception comes.Also please verify ID_CAP_MEDIALIB_AUDIO capability added or not.
FYI

How to avoid Filewatcher lock file during System.IO.File.Copy

I had developed a filewatcher program to monitor a folder, if there are any changed of the file, it will copy the file to another folder.
But I found that there will be error message when writing the original file (e.g. file being prcoess by another application...) it seems that the file locked when running [System.IO.File.Copy] copying to another folder.
Is there any solution can avoid the original file locked by the filewatcher/System.IO.File.Copy? Thanks.
The following is my code:
private void fileWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
if (lastWriteTime != lastRead)
{
txtLog.Text += e.ChangeType + ": " + e.FullPath + "\r\n";
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
try
{
string myPath = e.FullPath;
string myFile = e.Name;
System.IO.FileInfo myFileInfo = new System.IO.FileInfo(myFile);
string myAttibs = myFileInfo.Attributes.ToString();
System.IO.File.Copy(myPath, #"D:\\Folder\\Output\\" + myFile, true);
lastRead = lastWriteTime;
}
catch (System.IO.IOException ex)
{
System.IO.IOException myex = ex;
}
catch (System.Exception ex)
{
System.Exception myex = ex;
}
}
}
I ran into the same problem. I am not fond of my solution, as it feels hackish. But it works:
FileSystemWatcher fsWatcher = new FileSystemWatcher();
fsWatcher.Created += new FileSystemEventHandler( fsWatcher_Created );
private void fsWatcher_Created( object sender, FileSystemEventArgs e )
{
RaiseFileFoundEvent( e.FullPath );
while ( !TestOpen( e.FullPath ) ) ;
RaiseFileCopyDoneEvent( e.FullPath );
}
private bool TestOpen( string filename )
{
try
{
FileStream fs = new FileStream( filename, FileMode.Open,
FileAccess.Write, FileShare.None );
fs.Close();
return true;
}
catch ( Exception )
{
return false;
}
}
private void RaiseFileFoundEvent( string fullPath )
{
// a file is found, but the copy is not guaranteed to be finished yet.
}
private void RaiseFileCopyDoneEvent( string fullPath )
{
// the file is found, and we know the copy is done.
}
There's not a good way to solve this problem. How should the program behave if you're in the middle of copying the file to a new location when another application wants to write to it?
If you're willing to copy a corrupted file (that was written-to while you were copying), you'll have to write your own Copy method that uses FileShare.ReadWrite.

Categories

Resources