How to extract dot app(.app) mac file from a zip programmatically? - macos

I am working on a Unity project & facing an issue.
I have a zip file containing mybuild.app (mac) file.
I am using SharpZipLib to uncompress the zip file. Issue is, when lib uncompressing, it actually taking mybuild.app as a folder & create a directory with same name & its sub files & folders. After uncompressing mybuild.app is not being able to start.
I think the issue is with .app signature or something. I shouldn't extract .app file content separately.
Please tell me how can i get mybuild.app file from zip which actually works.
I am using Unity 3.5.6 on mac.
Here is my code:
using (ZipInputStream s = new ZipInputStream(File.OpenRead(a_filePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
Console.WriteLine(theEntry.Name);
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
// create directory
if (directoryName.Length > 0)
{
Debug.Log("Creating Director: " + directoryName);
Directory.CreateDirectory(directoryName);
}
if (fileName != String.Empty)
{
string filename = a_extractPath;
filename += theEntry.Name;
Debug.Log("Unzipping: " + filename);
using (FileStream streamWriter = File.Create(filename))
{
int size = 2048;
byte[] fdata = new byte[2048];
while (true)
{
size = s.Read(fdata, 0, fdata.Length);
if (size > 0)
{
streamWriter.Write(fdata, 0, size);
}
else
{
break;
}
}
}
}
}
}

Related

Slash xamarin issue

I am trying to get values from a specified route to load it in a collectionView. I don't know why Xamarin add a / to my path at the beggining. I am desesperate, I've tried to replace the /, differents ways to obtain the path, in differents places (inside the project, in the desktop) and any works. I think the problem could be the MonoAndroid file or some dll but I am not sure.
Differents things I've tried:
1:
StreamReader sr = new StreamReader("./ficheroPruebaXautoCB.txt");
string linea;
// Read the file and display it line by line.
while ((linea = sr.ReadLine()) != null)
{
ubicaciones.Ubication = linea.Substring(27, 33);
ubicaciones.Values = linea.Substring(0, 26) + linea.Substring(34, 48);
listUbicaciones.Add(ubicaciones);
counter++;
}
sr.Close();
2:
string path = "F:\\Xamarin\\Pruebas_fichero\\ficheroPruebaXautoCB.txt";
string path2 = #"F:\Xamarin\Pruebas_fichero\ficheroPruebaXautoCB.txt";
foreach (string line in System.IO.File.ReadLines(path2))
{
ubicaciones.Ubication = line.Substring(27, 33);
ubicaciones.Values = line.Substring(0, 26) + line.Substring(34, 48);
listUbicaciones.Add(ubicaciones);
counter++;
}
3:
string nombreArchivo = "ficheroPruebaXautoCB.txt";
string ruta = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
string rutaCompleta = Path.Combine(ruta, nombreArchivo);
if (File.Exists(rutaCompleta))
{
using (var lector = new StreamReader(rutaCompleta, true))
{
string textoLeido;
while ((textoLeido = lector.ReadLine()) != null)
{
ubicaciones.Ubication = textoLeido.Substring(27, 33);
ubicaciones.Values = textoLeido.Substring(0, 26) + textoLeido.Substring(34, 48);
listUbicaciones.Add(ubicaciones);
counter++;
}
}
}
4:
string ruta = "C:\\Users\\H_L\\Desktop\\ficheroPruebaXautoCB.txt";
try
{
//FileStream f = File.OpenRead(ruta);
var text = File.ReadLines(ruta, Encoding.UTF8);
foreach (string line in text)
{
ubicaciones.Ubication = line.Substring(27, 33);
ubicaciones.Values = line.Substring(0, 26) + line.Substring(34, 48);
listUbicaciones.Add(ubicaciones);
}
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
And the error:
"Could not find file "/C:\Users\H_L\Desktop\ficheroPruebaXautoCB.txt""
All these solutions have worked in a console C# project, so the problem is when I try to do it with Xamarin.
It seems that you can't access the file in your pc with the path for the android. You need to provide a path which the Android can use.
At first, you need to copy the local file into the simulator. You can check the following link : How to access local files of the filesystem in the Android emulator?
And then, if the file is in the app's own folder, you can access it without any storage permission. But when the file is in the other folders, you need to grant the read and write storage permission to your app.
You can check my old answer in the following link:How to open SQLite DB created by one Xamarin Android app in another app?

How to download a jar from artifactory with gradle to project directory?

What is the correct way to write a gradle task which downloads a .jar(or any other) file from artifactory to project directory(if file does not already exists)?
For example, I have a project with path /root/project with file /root/project/build.gradle inside. I want to download generator.jar from artifactory (com/company/project/generator/1.0) to /root/project directory if /root/project/generator.jar is not present.
tasks.register("downloadGeneratorJar") {
group = 'Download'
description = 'Downloads generator.jar'
doLast {
def f = new File('generator.jar')
if (!f.exists()) {
URL artifactoryUrl = new URL('myurl')
HttpURLConnection myURLConnection = (HttpURLConnection)artifactoryUrl.openConnection()
String userCredentials = gradle.ext.developerUser + ":" + gradle.ext.developerPassword
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()))
myURLConnection.setRequestProperty ("Authorization", basicAuth)
InputStream is = myURLConnection.getInputStream()
new FileOutputStream(f).withCloseable { outputStream ->
int read
byte[] bytes = new byte[1024]
while ((read = is.read(bytes)) != -1) {
outputStream.write(bytes, 0, read)
}
}
}
}
}

Xamarin Android - Write to file - access denied

I'm getting path to save a video .mp4 file by using the following code in PCL project, which return "/storage/emulated/0/DCIM/":
#if __ANDROID__
var dir = Android.OS.Environment
.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
var publicPath= dir.AbsolutePath;
var newFilepath = System.IO.Path.Combine(publicPath, fileName);
video.path = newFilepath;
#endif
I've added permissions to Android.Manifest as bellow:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And this function will get the .mp4 file from internet and save to the path:
public void downloadVideo(VideoInfor video, bool isRetried)
{
if (!video.downloadUrl.Contains(HLS) && !video.downloadUrl.Contains(HLS_1))
{
string filepath = video.path;
if (Uri.IsWellFormedUriString(video.downloadUrl, UriKind.RelativeOrAbsolute) && !video.downloadUrl.Contains("https://v.vnecdn.net/vnexpress/video/video_default.mp4"))
{
video.downloadUrl = video.downloadUrl.Replace("&", "&");
Console.WriteLine("Downloading url: " + video.downloadUrl);
try
{
if (!video.downloadUrl.Contains(".m3u8"))
{
Console.WriteLine("Downloading.....");
var request = (HttpWebRequest)WebRequest.Create(video.downloadUrl);
if (isRetried)
{
request.Timeout = 120000;
}
using (WebResponse response = request.GetResponse())
{
using (Stream source = response.GetResponseStream())
{
using (FileStream target = File.Open(filepath, FileMode.Create, System.IO.FileAccess.Write))
{
var buffer = new byte[1024];
bool cancel = false;
int bytes;
int copiedBytes = 0;
while (!cancel && (bytes = source.Read(buffer, 0, buffer.Length)) > 0)
{
target.Write(buffer, 0, bytes);
copiedBytes += bytes;
}
}
}
}
}
else
{
}
}
catch (Exception ex)
{
Console.WriteLine("Exception download url = " + video.downloadUrl);
Console.WriteLine("Exception download url Exception = " + ex.ToString());
if (!isRetried)
{
downloadVideo(video, true);
}
}
}
}
}
When the program running into "target.Write(buffer, 0, bytes);" I get the exception "Access to the path is denied", so anyone plesae tell me why is this error happening?
I already tried Plugin.permissions:
Dictionary<Permission, PermissionStatus> results =
await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
PermissionStatus status = results[Permission.Storage];
but I got "status = Permission.Unknow"
I already tried to save the video to a private path that only my application can access following code, which return "/data/user/0/com.companyname.VideoDownloader/files/":
var dir = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
video.path = System.IO.Path.Combine(dir, filename);
And downloadVideo function can be able to write all the bytes data into the path with no error, but I cannot see any files when browse to that path.
Here is my SDK configuration:
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="25" />
Since your target sdk is 25, you have to request permissions at runtime. You could refer to this blog for how to do it in xamarin.
I had all of the above things about permission enabled in my project and it still wouldn't let me write to files, just read them.
My solution: you have to use Path.Combine in the File.WriteAllText(..) even though you pass a string variable in the File.WriteAllText(path), you still need to write it as File.WriteAllText(Path.Combine(path))

Unzip a file in kotlin script [.kts]

I was toying with the idea of rewriting some existing bash scripts in kotlin script.
One of the scripts has a section that unzips all the files in a directory. In bash:
unzip *.zip
Is there a nice way to unzip a file(s) in kotlin script?
The easiest way is to just use exec unzip (assuming that the name of your zip file is stored in zipFileName variable):
ProcessBuilder()
.command("unzip", zipFileName)
.redirectError(ProcessBuilder.Redirect.INHERIT)
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
.start()
.waitFor()
The different approach, that is more portable (it will run on any OS and does not require unzip executable to be present), but somewhat less feature-full (it will not restore Unix permissions), is to do unzipping in code:
import java.io.File
import java.util.zip.ZipFile
ZipFile(zipFileName).use { zip ->
zip.entries().asSequence().forEach { entry ->
zip.getInputStream(entry).use { input ->
File(entry.name).outputStream().use { output ->
input.copyTo(output)
}
}
}
}
If you need to scan all *.zip file, then you can do it like this:
File(".").list { _, name -> name.endsWith(".zip") }?.forEach { zipFileName ->
// any of the above approaches
}
or like this:
import java.nio.file.*
Files.newDirectoryStream(Paths.get("."), "*.zip").forEach { path ->
val zipFileName = path.toString()
// any of the above approaches
}
this code is for unziping from Assets
1.for unzping first u need InputStream
2.put it in ZipInputStream
3.if directory is not exist u have to make by .mkdirs()
private val BUFFER_SIZE = 8192//2048;
private val SDPath = Environment.getExternalStorageDirectory().absolutePath
private val unzipPath = "$SDPath/temp/zipunzipFile/unzip/"
var count: Int
val buffer = ByteArray(BUFFER_SIZE)
val context: Context = this
val am = context.getAssets()
val stream = context.getAssets().open("raw.zip")
try {
ZipInputStream(stream).use { zis ->
var ze: ZipEntry
while (zis.nextEntry.also { ze = it } != null) {
var fileName = ze.name
fileName = fileName.substring(fileName.indexOf("/") + 1)
val file = File(unzipPath, fileName)
val dir = if (ze.isDirectory) file else file.getParentFile()
if (!dir.isDirectory() && !dir.mkdirs())
throw FileNotFoundException("Invalid path: " + dir.getAbsolutePath())
if (ze.isDirectory) continue
val fout = FileOutputStream(file)
try {
while ( zis.read(buffer).also { count = it } != -1)
fout.write(buffer, 0, count)
} finally {
val fout : FileOutputStream =openFileOutput(fileName, Context.MODE_PRIVATE)
fout.close()
}
}
for unziping from externalStorage:
private val sourceFile= "$SDPath/unzipFile/data/"
ZipInputStream zis = null;
try {
zis = new ZipInputStream(new BufferedInputStream(new
FileInputStream(sourceFile)));
ZipEntry ze;
int count;
byte[] buffer = new byte[BUFFER_SIZE];
while ((ze = zis.getNextEntry()) != null) {
String fileName = ze.getName();
fileName = fileName.substring(fileName.indexOf("/") + 1);
File file = new File(destinationFolder, fileName);
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Invalid path: " +
dir.getAbsolutePath());
if (ze.isDirectory()) continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}
}
} catch (IOException ioe) {
Log.d(TAG, ioe.getMessage());
return false;
} finally {
if (zis != null)
try {
zis.close();
} catch (IOException e) {
}
}
return true;

Open a project file in phone7

Howdy,
I have a project in VisualStudio which contains a folder 'xmlfiles' below the root node. This folder contains a file 'mensen.xml' which I try to open ...
However when I try to open that very file the debugger steps in and throws an exception.
I tried it with
if(File.Exists(#"/xmlfiles/mensen.xml") )
{
bool exists = true;
}
as well as:
FileStream fs = File.Open("/xmlfiles/mensen.xml", FileMode.Open);
TextReader textReader = new StreamReader(fs);
kantinen = (meineKantinen)deserializer.Deserialize(textReader);
textReader.Close();
Nothin is working :(.
How can I open a local file in the Phone7 Emulator?
If you are just opening it to read it then you can do the following (Assuming you have set the Build Action of the file to Resource):
System.IO.Stream myFileStream = Application.GetResourceStream(new Uri(#"/YOURASSEMBLY;component/xmlfiles/mensen.xml",UriKind.Relative)).Stream;
If you are attempting to read/write this file then you will need to copy it to Isolated Storage. (Be sure to add using System.IO.IsolatedStorage)
You can use these methods to do so:
private void CopyFromContentToStorage(String fileName)
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
System.IO.Stream src = Application.GetResourceStream(new Uri(#"/YOURASSEMBLY;component/" + fileName,UriKind.Relative)).Stream;
IsolatedStorageFileStream dest = new IsolatedStorageFileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, store);
src.Position = 0;
CopyStream(src, dest);
dest.Flush();
dest.Close();
src.Close();
dest.Dispose();
}
private static void CopyStream(System.IO.Stream input, IsolatedStorageFileStream output)
{
byte[] buffer = new byte[32768];
long TempPos = input.Position;
int readCount;
do
{
readCount = input.Read(buffer, 0, buffer.Length);
if (readCount > 0) { output.Write(buffer, 0, readCount); }
} while (readCount > 0);
input.Position = TempPos;
}
In both cases, be sure the file is set to Resource and you replace the YOURASSEMBLY part with the name of your assembly.
Using the above methods, to access your file just do this:
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
if (!store.FileExists(fileName))
{
CopyFromContentToStorage(fileName);
}
store.OpenFile(fileName, System.IO.FileMode.Append);
The emulator does not have access to the PC file system. You must deploy the file to the target (emulator). The easiest way to do this is mark the file as an embedded Resource. Set the file's Build Action to 'Resource' and then extract it at runtime with code something like this:
var res = Application.GetResourceStream(new Uri([nameOfYourFile], UriKind.Relative))

Resources