Context.GetExternalFilesDir() is not accepting null - c#

I am trying to get the path to the private external storage directory of my c# xamarin android app. The microsoft docs tell us to use
Android.Content.Context.GetExternalFilesDir(string)
However, when I try to use this function, I get the following error regarding that function:
An object reference is required for the non-static field, method or property
This is my code
class RecorderController {
string externalStoragePath;
public RecorderController() {
externalStoragePath = Path.Combine(Context.GetExternalFilesDir(null), "recordings");
// I have also tried the following:
// string s = null;
// externalStoragePath = Path.Combine(Context.GetExternalFilesDir(s), "recordings");
// Even when I try to get the path to the Downloads folder, I get the same error:
// string s = Android.OS.Environment.DirectoryDownloads;
// externalStoragePath = Path.Combine(Context.GetExternalFilesDir(s), "recordings");
}
}
I have no clue how to solve this, does anybody know what I am doing wrong?

Try to change
externalStoragePath = Path.Combine(Context.GetExternalFilesDir(null), "recordings");
to
externalStoragePath = Path.Combine(GetExternalFilesDir(null).AbsolutePath, "recordings");

Apparently I had to use an instance of Context, like Mike Christensen commented. I also missed that GetExternalFilesDir returns a File object, and that I should use AbsolutePath after it, like Leo Zhu said.
I changed my code to
class RecorderController {
string externalStoragePath;
public RecorderController(Context con) {
PermanenteOpslagPad = Path.Combine(con.GetExternalFilesDir(null).AbsolutePath, "recordings");
}
}

Related

New to c# need to understand How can I Fix this error? "Possible null reference return" I've tried every option in visual studio and nothing fixed it

Learning C# should this be fixed or left alone? I can't seem to find an answer that works every action in VS didn't resolve the issue answer's I found online I either didn't understand or failed as well. Why I am asking here.
`
public class AdventureService : IAdventureService
{
public Adventure GetInitialAdventure()
{
var basePath = $" {AppDomain.CurrentDomain.BaseDirectory}Adventures";
var initialAdventure = new Adventure();
if (File.Exists($"{basePath}\\initial.json"))
{
var directory = new DirectoryInfo(basePath);
var initialJsonFile = directory.GetFiles("initial.json");
using (StreamReader fi = File.OpenText(initialJsonFile[0].FullName))
{
initialAdventure = JsonConvert.DeserializeObject<Adventure>(fi.ReadToEnd());
}
}
return initialAdventure;
}
`
You need to decide what the method will do if the deserialize call returns null.
One option is for the method to return null, in which case you just need to change the return type:
public Adventure? GetInitialAdventure()
{
//Etc.
If you prefer that the method never return null, you could change the return statement so that it replaces a null with a new Adventure.
//Rest of method up here
return initialAdventure ?? new Adventure();
}
There are maybe other options as well but these are the basics.

How can I move this function into a Class

public string F03_veri_textbox(string veriadi3)
{
string Veritext;
Veritext = webBrowser_sample.Document.GetElementById(veriadi3).GetAttribute("value");
return Veritext;
}
I have a webBrowser_sample object in Form1. I use this function to collect data from specific webpage. It is working properly.
I want to use this function from a class.
But when I try to move it, C# says "The name 'webBrowser_sample' does not exist in the current context".
If I define a new webBrowser_sample in the Class, it will create new webBrowser_sample object.
So I can't use it because I use this function to collect data while I am surfing this browser.
Replace 'mytype' with the object type that webBrowser_sample is. You need to pass in a reference to the object, as in the code below. Another option would be to use an extension method.
public string F03_veri_textbox(string veriadi3, mytype browser)
{
string Veritext;
Veritext = browser.Document.GetElementById(veriadi3).GetAttribute("value");
return Veritext;
}

C# String Property and string literal concatenation issue

I am a bit new at C# and I have run into a string concatenation issue. I am hoping someone might be able to give me a hint and help me resolve this. I have searched Google extensively and have spent more than a week on this so any help/advice would be greatly appreciated.
I have created a custom PathEditor for a string property. The property basically allows the user to key in a file to use in the app. If the file typed in is correct, it shows in the property cell as it should. What I am trying to do is output to the property cell an error message if the file typed in does not exist - I check this in my file validator. Here is the string literal issue.
If I use:
return inputFile+"Error_";
this works OK and I get the outpur file123.txtError_ in the property grid cell.
If I use:
return "Error_"+inputFile;
I get only the inputFile without the literal "Error_". Sot he property grid cell shows file123.txt in the property grid cell.
I have checked and inputFile is a string type. Any ideas as to why this is happening?
Also, is there any way to change to font, and/or, color of the message output? I tried to change the background of the property grid cell and I understand that this is not possible to do.
Thank you.
Z
More of the code:
[
Description("Enter or select the wave file. If no extension, or a non .wav extension, is specified, the default extension .wav will be added to the filename."),
GridCategory("Sound"),
Gui.Design.DisplayName ("Input Sound"),
PathEditor.OfdParamsAttribute("Wave files (*.wav)|*.wav", "Select Audio File"),
Editor(typeof(PathEditor), typeof(System.Drawing.Design.UITypeEditor))
]
public string InputWavefile
{
get { return System.IO.Path.GetFileName(inputtWavefile); }
set
{
if (value != inputWavefile) // inputWavefile has been changed
{
// validate the input stringg
_inputWavefile = FileValidation.ValidateFile(value);
// assign validated value
inputWavefile = _inputWavefile;
}
}
}
My guess is that you've got a funky character at the start of inputFile which is confusing things - try looking at it in the debugger using inputFile.ToCharArray() to get an array of characters.
The string concatenation itself should be fine - it's how the value is being interpreted which is the problem, I suspect...
I'm guessing your filename looks something like this, C:\Folder\FileName.txt when you start out.
In your FileValidation.ValidateFile() method you
return "Error_" + InputFileName;
it now looks like this: Error_C:\Folder\FileName.txt.
So, when you run the line below,
get { return System.IO.Path.GetFileName( _inputWavefile ); }
it strips off the path and returns the filename only, FileName.txt.
Even when the filename is not valid, you are still running System.IO.Path.GetFileName() on it.
Assuming this is a PropertyGrid in winforms app. Then it's neither a string concatenation issue, nor PropertyGrid issue, as could be proven by the following snippet. So you need to look elsewhere in your code:
public partial class Form1 : Form {
PropertyGrid pg;
public Form1() {
pg = new PropertyGrid();
pg.Dock = DockStyle.Fill;
this.Controls.Add(pg);
var inputFile = "some fileName.txt";
var obj = new Obj();
obj.One = "Error_" + inputFile;
obj.Two = inputFile + "Error_";
pg.SelectedObject = obj;
}
}
class Obj {
public string One { get; set; }
public string Two { get; set; }
}

ESRI AppRef Throws Com 8000FFFF error

i am using the arcGIS api to make a plugin for arcFM, when i try to run this code
Type t = Type.GetTypeFromProgID("esriFramework.AppRef");
System.Object obj = Activator.CreateInstance(t);
pApp = obj as IApplication;
i get
System.Runtime.InteropServices.COMException(0x8000FFFF): Creating an instance of the component with CLSID {Appref CLSID HERE} from the IClassFactory faileddue to the following error: 8000ffff
Thanks
This was impossible i needed to be using arcMap not ArcFM
In the AppRef CoClass documentation, it says:
Note you can only use the AppRef
object if your code is running inside
one of the ArcGIS application
processes.
Forum posts seem to confirm that this is the same error which is seen when this constraint has been violated:
From http://forums.esri.com/Thread.asp?c=93&f=1729&t=217861:
It is my understanding that there is
indeed no way to access the
IApplication instance from a
geoprocessing script.
In theory, if your task is purely
geoprocessing, you should be able to
do it all without accessing the
IApplication object.
It looks like the OP of the above forum post was able to get around their problem by "using IToolboxWorkspace and accessing directely the Esri-toolboxes". This was her code:
public IGPTool GetTool(string _sToolName, string _sToolboxName)
{
IWorkspaceFactory pGPTFact;
IToolboxWorkspace pToolboxWorkspace;
IGPToolbox pGPToolbox;
IGPTool pGPTool;
pGPTFact = new ToolboxWorkspaceFactoryClass();
pToolboxWorkspace = pGPTFact.OpenFromFile(
ArcGISInstallFolder + #"\ArcToolbox\Toolboxes", 0) as IToolboxWorkspace;
pGPToolbox = pToolboxWorkspace.OpenToolbox(_sToolboxName);
pGPTool = pGPToolbox.OpenTool(_sToolName);
return pGPTool;
}
private string ArcGISInstallFolder
{
get
{
if (string.IsNullOrEmpty(this.m_sArcGISInstallFolder))
{
Microsoft.Win32.RegistryKey regkey;
regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
#"Software\ESRI\ArcGIS", false);
this.m_sArcGISInstallFolder = regkey.GetValue("InstallDir") as String;
}
return this.m_sArcGISInstallFolder;
}
}
Perhaps you can accomplish your goal either without the AppRef object or by running your script from inside the application.

C# class objects

I have a class that I am using below. And I am using this class for my windows application. However, when I call the method from my application ReadInConfig() it successfully reads and fills the datatable, and assigns the _sip_ip address.
In my windows application I have the following. However, it doesn't give me the sip_ip that it has been assigned.
ConfigSIP readIn = new ConfigSIP();
readIn.ReadInConfig();
string sip_ip = readIn.sip_ip(); // Get nothing here.
I am thinking as the _sip_ip that has been assigned by the data table is a different object than doing this readIn.sip_ip();
Is there any way I can solve this problem?
Many thanks,
public class ConfigSIP
{
private string _sip_ip;
// Fill the data table and assign the sip ip.
public void ReadInConfig()
{
DataTable dt = new DataTable("Admin");
dt.ReadXmlSchema(#"C:\Config.xml");
dt.ReadXml(#"C:\Config.xml");
_sip_ip = dt.Rows[0]["Sip_ip"].ToString();
}
// Return the sip ip address.
public string sip_ip()
{
return _sip_ip;
}
}
You forgot to call ReadInConfig:
ConfigSIP readIn = new ConfigSIP();
readIn.ReadInConfig();
string sip_ip = readIn.sip_ip();
If your code is copied verbatim your client code isn't calling the ReadInConfig() method. So the string will never get populated.

Categories

Resources