Open a .txt file on Android - c#

I am currently working in Unity3D and wish to simply open a .txt file upon clicking on a button.
EDIT : When I say open a .txt file, I mean open it in some editor on the device, not open it asnd save it's content to some string in my app. Kind of like opening a browser to access a website from the app.
Here's the code I currently have (C#) :
private void ShowTextFile(string fileName)
{
Application.OpenURL(Application.streamingAssetsPath + "/PATH/" + fileName);
}
But it's not working ! What am I missing ?
EDIT : I'm expecting for the .txt file to open in another window (like opening a web browser, for example), but it simply isn't doing anything. Not even getting an error.
EDIT2 : I tried using Application.persistentDataPath instead, and in both cases, it says my .txt file doesn't exist. However, when using Application.persistentDataPath, it opens up a message box asking me what I want to open the file with. Whatever I choose, it will give me an error, telling me error loading file or something like that. I've also noticed that it opens "file:///". Is it normal that there is a file:/// before the path ?
EDIT3 (I'm on fire !) : I think the problem might be related to the fact that there is a "." in my path (the com.me.myapp in the data path). Is there any way to avoid this ? Am I even looking at the right path ?

I've tried opening a txt file on Android before, using this:
TextAsset txt = (TextAsset)Resources.Load("file", typeof(TextAsset));
string content = txt.text;
Where file is the name of the txt file (don't need to write file.txt).
The variable string will contain the contents of the text file, you just need to loop through them afterwards.
This method requires:
using System.Text;
using System.IO;
Put file.txt inside a directory named "Resources" (inside Assets dir), if it isn't there then create a new one.

This is my code for Android:
var rpath = Path.Combine(Application.streamingAssetsPath, "file_name");
WWW www = new WWW(rpath);
yield return www;
StringReader streamReader = new StringReader(www.text);
text = streamReader.ReadToEnd();
For iOS:
var rpath = Path.Combine(Application.streamingAssetsPath, "file_name");
StreamReader streamReader = new StreamReader(rpath);
text = streamReader.ReadToEnd();
Note: file_name in StreamingAssets folder

Found a solution that works ! Here's the thing, the streaming assets path, on Android, returns a path that can only be read by a WWW object. So I simply read it with a WWW object then recreated the file in my persistent data path. Added a check to make sure the file doesn't already exist before creating it. Also, make sure you create the directory in case it doesn't exist, else you'll get an error. Note that this solution is probably not optimal if you have large files that are regularly accessed.
string realPath = Application.persistentDataPath + "/PATH/" + fileName;
if (!System.IO.File.Exists(realPath))
{
if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PATH/"))
{
System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PATH/");
}
WWW reader = new WWW(Application.streamingAssetsPath + "/PATH/" + realPath);
while ( ! reader.isDone) {}
System.IO.File.WriteAllBytes(realPath, reader.bytes);
}
Application.OpenURL(realPath);
If anyone has anything to add to this answer, feel free !

Related

Getting the contents of a file in Visual Studio without opening the file from an extension

I'm trying to read the contents of a file in a Visual Studio extension. The following code works, but forces me to open the file, if it isn't (otherwise it crashes):
textDocument = (TextDocument)projectItem.Document.Object("TextDocument");
EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
string text = editPoint.GetText(textDocument.EndPoint);
I can get the path of the project, so I suppose I could make an educated guess as to the location of the project item. However, ideally I'd like to either get the file contents without opening it; or, alternatively, get the path to the project item (then I could just use System.IO to access the file contents).
I've looked, but don't seem to be able to find any mention of either of these. Can anyone point me in the right direction, please?
You can get the path from a ProjectItem by reading its properties.
var path = YourProjectItem.Properties.Item("FullPath").Value.ToString()
After you have the path you can read its content with System.IO.
string content = File.ReadAllText(path);
If the file is somewhat larger and you are getting troubles with the current code due to size, you should take a look at the StreamReader class.
I'm not sure if this is possible for extensions but you could probably use System.IO, like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
string fileText = File.ReadAllText(filePath);
You could also use StreamReader like this:
using System.IO;
string filePath = #"C:\Whatever\YourFileName.txt";
using (StreamReader sr = new StreamReader(filePath))
fileText = sr.ReadToEnd();
EDIT:
I think I understand you better now.
The only way to "get the file contents without opening it" would be if the extension were to give you that data actively, but I can safely assume it doesn't.
When reading a file, you should already know where the file is (if you don't know then either you're not intended to access that file or you just haven't looked long enough).
I'd try searching the SDK files manually (Or with a file crawler).

Storing MSSQL LocalDB for Application

I have been using a LocalDB.mdf file to build my application, but now need to use it in production and create an installable application.
After research, it seems the best place to store such a file is in the /Appdata/Local/ folder.
I intend to create a new LocalDB.mdf file in there if it doesnt already exist, or has been deleted.
I have a pre-made LocalDB.mdf file in my App Resources, which I wanted to copy into this /Appdata/Local/ folder on first run, but I am seeing an Access is denied error.
I can create a blank file ok to that folder.
Here is the code:
string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string dvAppDataFolder = appDataFolder + #"\MyApp";
AppDomain.CurrentDomain.SetData("DataDirectory", dvAppDataFolder);
if (!Directory.Exists(dvAppDataFolder))
Directory.CreateDirectory(dvAppDataFolder);
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
{
File.WriteAllBytes(dvAppDataFolder, LokiServer.Properties.Resources.newDB);
}
In addition, Am I going about this the right way?
This line
if (!File.Exists(dvAppDataFolder + "LocalDB.mdf"))
is probably wrong. Missing the backslash, better to use Path.Combine instead of a string concatenation.
Finally, you want to write to a file not to a folder
string fileName = Path.Combine(dvAppDataFolder,"LocalDB.mdf");
if (!File.Exists(fileName))
{
File.WriteAllBytes(fileName, LokiServer.Properties.Resources.newDB);
}
Are you doing it right? It depends. If your app data should be kept separated for each user of your target machine then you are right, but if you want your database to be available to all users of that machine then use
string appDataFolder = Environment.GetFolderPath
(Environment.SpecialFolder.CommonApplicationData);

how to Save File using C# Windows Application

I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));

reading and writing txt file publish problems c#

I have been using external txt files to save the score and the player name (I only save one score and one name in two different files)
When there is a new highscore it saves over the old one. I had it all working perfectly until I published the project, now it cant locate the file.
I embedded the txt file but I cant write to it.
I am using the following code.
using (StreamWriter write = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "highscore.txt")) // read the high score text file
{
write.WriteLine(player.score); // saves the new high score
write.Close(); // closes the file
}
using (StreamWriter write = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "nickname.txt")) // reads the high score text file
{
write.WriteLine(player.nickname); // save new highscore name
write.Close(); // close file
}
When I run the games from a USB or a CD they wont read -
So my question is - how to I place the txt files into a directory my game can see/find?
When you are running your program from the CD, your application's path is on that CD, so the code:
AppDomain.CurrentDomain.BaseDirectory + "highscore.txt"
points to a readonly CD path.
in order to be able to save the file properly, you can:
ask user to enter a path to which he/she wants the data to be saved
use one of the available directories (look in the Environment class),
for instance using the:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Please also note that it is better to use Path.Combine() to concat the paths rather than '+' sign.

Get full path from an opened file - C#

I'm working with print jobs using PrintSystemJobInfo and this class doesn't have the path of the file (print job). So, I was wondering if there is a class where I can use the filename that is open (in memory) and this class return the full path. This file opened could be .doc, .pdf, .xls, .txt, and so on.
Please, someone can point me to the right direction or have an idea... it would be very helpful...
The only way for you to find open file handles is to use the NtQuerySystemInformation call. Here is a project that has this done as an explorer context menu. In this guy's case, he looks for files open in a specific folder.
You would then have to match the file name to the file you have in your print job.
By the way, this is not C# but you can wrap and call the same calls he is using. The rest is really up to you to figure out. ;)
Assuming you have a Stream object that is a FileStream then just do a cast and interrogation:
Stream str = printJob.JobStream;
FileStream fileStream = str as FileStream
if( fileStream != null ) {
String fileName = fileStream.Name;
}

Categories

Resources