Slash xamarin issue - xamarin

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?

Related

Rename a recorded file every time I save a record in xamarin

I am saving my records using this code:
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
public string fileName { get; set; }
fileName = Path.Combine(path, "sample.wav");
if (!recorder.IsRecording)
{
recorder.StopRecordingOnSilence = TimeoutSwitch.IsToggled;
//Start recording
var audioRecordTask = await recorder.StartRecording();
BtnDoneRec.IsEnabled = false;
await audioRecordTask;
RecEditor.IsEnabled = true;
BtnDoneRec.IsEnabled = false;
PlayButton.IsEnabled = true;
var filePath = recorder.GetAudioFilePath();
if (filePath != null)
{
var stream = recorder.GetAudioFileStream();
using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
}
}
}
else
{
//stop recording ...
await recorder.StopRecording();
}
I want my record to have a specific name which is labeled with my RecEditor
using (var streamReader = new StreamReader(fileName))
{
File.Move("sample.wav", RecEditor.Text + ".wav");
}
So it will rename "sample.wav" to "RecEditor text.wav" every time I click my save button.
But when I click save, it gives me this record
System.IO.FileNotFoundException: 'Could not find file '/sample.wav'.'
The record is stored in /storage/emulated/0/sample.wav
The sample.wav is created in my device but I don't know why it give me 'Could not find file '/sample.wav'.' error. What am i doing wrong here?
I believe that what you're looking is something like this:
if(File.Exists(fileName))
{
var newFileName = Path.Combine(path, $"{RecEditor.Text}.wav");
File.Move(fileName, newFileName);
}
You don't need to open a new Stream as you are doing. Also, you need to put the full file path not only the file name.
You might want to validate that RecEditor.Text is not empty before using its value for the newfileName
Hope this helps.-

CreateChooser is not working in Android v5.1

I am using intent to share pdf files. I am restricting apps when share file. I want to share the file to Good document, Kindle and drop box alone. I am using the below code to achieve this.But the below code is not working in android v5.1. The device have the required app to share. But it is showing "No apps can perform this action" when share. Can you anyone suggest your ideas to resolve this?
var pathFile = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var m_documentMobiNames = shortName + "." + fileType;
var mobileFileName = Path.Combine(pathFile, m_documentMobiNames);
var shareIntentsLists = new List<Intent>();
Intent sendIntent = new Intent();
sendIntent.SetAction(Intent.ActionSend);
sendIntent.SetType("application/pdf");
var resInfos = context.PackageManager.QueryIntentActivities(sendIntent, 0);
if (resInfos.Count > 0)
{
foreach (var resInfo in resInfos)
{
string packageName = resInfo.ActivityInfo.PackageName;
if (packageName.Contains("com.google.android.apps.docs") || packageName.Contains("com.dropbox.android") || packageName.Contains("com.amazon.kindle"))
{
Intent intent = new Intent();
intent.SetComponent(new ComponentName(packageName, resInfo.ActivityInfo.Name));
intent.SetAction(Intent.ActionSend);
intent.SetType("application/pdf");
intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + mobileFileName));
intent.SetPackage(packageName);
shareIntentsLists.Add(intent);
}
}
}
if (shareIntentsLists.Count > 0)
{
chooserIntent = Intent.CreateChooser(new Intent(), "Share with");
chooserIntent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse(mobileFileName));
chooserIntent.PutExtra(Intent.ExtraInitialIntents, shareIntentsLists.ToArray());
chooserIntent.SetFlags(ActivityFlags.ClearTop);
chooserIntent.SetFlags(ActivityFlags.NewTask);
context.StartActivity(chooserIntent);
await Task.FromResult(true);
}

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

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;
}
}
}
}
}
}

windows phone 7 updating isolated storage

In windows phone 7, what is the protocol for updated an isolated storage text file? Say I have 10 words in a text file arranged at 1 per line. Now suppose, the user uses the application and a new word needs to be stored on the fifth line. How do I write to the file, which already contains 10 words with 1 word per line?
Thanks in advance you guys are awesome.
The way I have been doing it is:
Read in a file from IsolatedStorage to menmory
Update the String
Write the file back to storage
Read in File
public static string ReadFromStorage(string filename)
{
string fileText = "";
try
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader sr = new StreamReader(new IsolatedStorageFileStream(filename, FileMode.Open, storage)))
{
fileText = sr.ReadToEnd();
}
}
}
catch
{
}
return fileText;
}
Write to File
public static void WriteToStorage(string filename, string text)
{
try
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string directory = Path.GetDirectoryName(filename);
if (!storage.DirectoryExists(directory))
storage.CreateDirectory(directory);
if (storage.FileExists(filename))
{
MessageBoxResult result = MessageBox.Show(filename + " Exists\nOverwrite Existing File?", "Question", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.Cancel)
return;
}
using (StreamWriter sw = new StreamWriter(storage.CreateFile(filename)))
{
sw.Write(text);
}
}
}
catch
{
}
}
So I would do:
string fileName = "Test.txt";
string testFile = IsolatedStorage_Utility.ReadFromStorage(fileName);
testFile = testFile.Replace("a", "b");
IsolatedStorage_Utility.WriteToStorage(fileName, testFile);
Writing to a file in Isolated Storage is basically a file write operation. It is similar as how you will access a normal file and read write to it in normal operating system. in your scenario if you are sure that you need to update 5th line out of 10 lines, you will read line by line using stream reader and will use stream writer to update the specific line that you want to update. You do not need to re-write all content again and again.
On the other hand if you just want to add new content you can just append it to end of file. You may find this link useful http://goo.gl/IKii5

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