Problem with data reading on android device [Xamarin Forms] - c#

I'm new in xamarin forms and I need to open/save some data. I chose interlanl storage, becosue it won't be a big database. Everything works fine I can save and then read fiel. The problem is showing when I'm trying to move the app from the computer to my smartphone. First, I don't understand why in the folder app/Android/bin/Debug (on my computer) there are two files with .apk extension. One is named "com.companyname.myapp.apk" and the other is named "com.companyname.myapp-Signed.apk". After moving these files to the main folder on my phone I can install only the second one, but after opening it on phone the app is closing immediately. I'm sure that the reason for that is reading file because when I remove the reading method from app, the app is opening normally. Another stranger thing (for me) is that when I plugged the phone into a computer using USB debugging and run the program from a visual studio everything is ok, even if I uninstall app and instal it using the file "com.companyname.myapp-Signed.apk". Here is my reading method:
var path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "test.txt");
if (!File.Exists(path))
{
var writer = new StreamWriter(path);
writer.Write("some data");
}
var reader = new StreamReader(path, true);
string data;
data = reader.ReadToEnd();
Above code is calling in constructor in MainPage.xaml.cs fiel, maybe that is important information.
Is it something in my code or the problem is in the project properties. As I read the app doesn't need any permission to works with internal storage, so I have no idea what is wrong.

Related

File activation in MAUI

I want users to be able to open a file using my MAUI app. For example in Windows they could right-click on the file in File Explorer, choose my app in "open with" and then my app would open the file.
I have put file type associations in the Windows app manifest, and it does successfully launch my app when the file is opened by the user in File Explorer.
My problem is, how do I get notified that the reason my app was launched was because they want to open a file, and how do I get the file path?
If this was a regular UWP app and not a MAUI app, I could overload Application.OnFileActivated and handle it there. However I have not been able to find that in MAUI. link to MAUI source
Should I try to handle this by overloadng MauiWinUIApplication.OnLaunched for the Windows version of my app? Or do I have to add handlers via ConfigureLifecycleEvents? Or somewhere else?
I see that OnLaunched is being triggered when I try to open my app with the file, but a) args.UWPLaunchActivatedEventArgs.Kind is always ActivationKind.Launch and never ActivationKind.File and b) the file path doesn't appear in the LaunchActivatedEventArgs object anywhere. Obviously if nothing else I will need to get the file path somehow.
Overloading MauiWinUIApplication.OnLaunched in App.xaml.cs was the correct approach, but the args it gets are buggy (they never have ActivationKind.File and never include the path to the file). A workaround for this bug is to get the real args from another API.
protected override void OnLaunched(LaunchActivatedEventArgs buggyArgs)
{
base.OnLaunched(buggyArgs);
var goodArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
switch (goodArgs.Kind)
{
case ExtendedActivationKind.File:
var data = goodArgs.Data as IFileActivatedEventArgs;
var paths = data.Files.Select(file => file.Path).ToArray();
// Do something
break;
}
}

C# file creation is not working after setup file is created

I have an app which is creating .json file. User enters required data and then app creates .json file inside bin folder:
File.WriteAllText("dbconfig.json", JsonConvert.SerializeObject(dbconfig, Newtonsoft.Json.Formatting.Indented));
Next time I start app the code reads bin folder using Environment.CurrentDirectory an searches for a .json file:
File.Exists($"{Environment.CurrentDirectory}\\dbconfig.json"
I am using this so that user shouldn't need to enter the same data everytime he starts an app, only once for the first time. While debugging everything is working fine. The problem is that after I've created setup file and install an application, after I enter required data to be saved to .json and press OK the application crashes.
Does anyone have an idea where the problem can be? Maybe something is wrong with file creation? I've never done such thing before so there is great possibility that I'm missing something in my code.
Almost impossible to say without more information like what is the exception? Is the error in the file create or json serialization.
Off the top of my head it could be dependent on where you install application. i.e. is it under a protected folder where you may need elevated privileges.
Looking at your filename looks like you want to store some user data, ideally those files should be stored in the users profile or all users profile. Try something like
// create a folder to store user data under c:\users\username\appdata\local
var appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "myapp");
if (!Directory.Exists(appDataPath))
{
Directory.CreateDirectory(appDataPath);
}
//Write json to file
var jsonFile = Path.Combine(appDataPath, "dbconfig.json");
File.WriteAllText(jsonFile, JsonConvert.SerializeObject(dbconfig, Newtonsoft.Json.Formatting.Indented));
//ToRead
if (File.Exists(jsonFile))
{
var jsonString = File.ReadAllText(jsonFile);
.....
}

windows explorer cant see files written by c# app File.WriteAllLines

I am having a strange problem that I am unable to access files written by my c# application. My app basically does :
var file = "C:\\Users\\Public\\Documents\\something.txt";
List<string> content = new List<string> { "one thing", "two things" };
Console.WriteLine(System.IO.File.Exists(file));
System.IO.File.WriteAllLines(file, content);
Console.WriteLine(System.IO.File.Exists(file));
The first time I run the app, the output is
False
True
Yet I cannot see the written file in Windows Explorer (Windows 10). I get no exceptions attempting to write the file. The second time I run the app, the output is :
True
True
According to my application the file is being written however Windows thinks differently. As a sanity check I spun up a second app that opens a dialog using OpenFileDialog. When I run that, I am able to see my written files! Windows explorer still cannot. Attached is a screenshot of windows explorer and my openfiledialog side by side.
If I go to notepad and browse for the file I cannot see it or manually type in the name.
Its been a long week of work, there must be some dumb explanation...? Help! :-)
Screenshot - windows explorer on left, c# app open dialog on right :
https://imgur.com/a/8ZTDIe6
per #BACON 's suggestion in the comments above I discovered that after disabling the Comodo anti-virus I am able to write and see my files.
I believe the software is running my app or either only allowing IO from my app in some kind of container. I need to figure out how to grant my apps proper permissions through the anti-virus software, but that was the culprit.

C# launching an external app with metro api

I am trying to develop an app which launches a regular .exe application from metro app using launcher class. MSDN provided a sample here and a stackoverflow sample is here
The problem is that my metro gives error of "file not found" even the file is there. i have tried to place file on other drives as well but the problem persists
here is my code sample
// Path to the file in the app package to launch
string imageFile = #"E:\App.exe";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
/* error in the above line .it says file not found The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)*/
if (file != null)
{
// Launch the retrieved file
var success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
LaunchFileAsync is for launching a file in its default program.
http://msdn.microsoft.com/library/windows/apps/Hh701461
I am not convinced it will work with an .exe
The correct usage is something like:
LaunchFileAsync("images\\picturesofcats.png");
This then opens a picture of cats in your default image viewer.
This will not work for an .exe due to sandboxing, and because .exe has no default opener.
There are a few tricks to get around this, see: Launching a Desktop Application with a Metro-style app
Generally, you are working against the design of Windows 8 to do this, so you might want to reconsider your approach.

Visual Studio - Cannot build a simple project more than once

When I try to build a project twice in successon, i get the following error
Error 2 Unable to copy file "obj\x86\Release\iFileUploader.exe"
to "bin\Release\iFileUploader.exe". The process cannot access the
file 'bin\Release\iFileUploader.exe' because it is being used by another process.
If I close Visual Studio and reopen it, I can compile it again but only once.
I have my projects hosted on a Windows network share. The server runs Windows 2008 R2 and Im on a Windows 7 machine and Ive tried setting everyone full control on the share and the folder permission, to no avail.
Ive even run the Unlocker program and checked the Windows Share & Storage Manager to see if anything is using it and nothing is! I cant delete the file when this happens either until I close VS.
Is there a setting I am missing in Visual Studio?!
UPDATE
Have removed all antivirus/antispam, disabled firewall.. so zero security.
Have disabled "Enable the Visual Studio hosting process"
Visual Studio is some how the colprupt with not releasing the handle
UPDATE
Another thread that has exactly the same problem but from years ago !!
Destroy process-less console windows left by Visual Studio debug sessions
UPDATE
I copied the files locally, and that didnt work. So I created a new project and then copied all the code in to the new project and now its working (with the files stored locally)
check your antivirus program is using it or not.
Alternatively use Process Explorer and find for the string - "iFileUploader.exe" and see who's using it. You can easily get the handle and close it.
Several points:
Check if you don't have a process iFileUploader.exe already running in the Windows Task Manager.
Check that nobody is not running a project that could use iFileUploader.exe.
Christian even if you are have your Stream in a using(){} do not declare a new variable of StreamReader for example do not do this
using(StreamReader streamReade = new StreamReader)
{
..... // if you do you will run into that stream being locked
}
//Declare the StreamReader variable out side of the using and then within the using do something like this.
StreamReader streamReader = null
using(streamReader = new StreamReader()
{
}
Make sure that where you have created an instance of the StreamReader or StreamWriter that you have closed the stream.
For example I would create at the application level a StreamReader / StreamWriter instance and set it to null
Class SomeClass
{
public StreamWriter streamwrtFileToCreate = null;
public FileStream fstreamFileStream = null
public SomeMethod(string FileName, string FilePath)
{
FileStream fstreamFileStream = new FileStream(#FileName + #FilePath, FileMode.Create);
streamwrtFileToCreate = new StreamWriter(fstreamUpdateRpt);
streamwrtUpdateRpt.AutoFlush = true;
}
}
Also it would help if you post the exact example of code that you are using when you create the FileStream Instance
I had this issue in VS 2012 windows 7.
Root cause is Avast Antivirus.
Fix is disable Avast whenever needed to work on C++ console
applications
(or)
->Go to Avast Settings
->Active Protection
->File System Shield (Customize)
->uncheck Scan programs when executing

Categories

Resources