When I build on Android my json files seems to not load because I dont see data. in unity editor play it works fine. I'm struggling with something thats working on PC but not on Android. Just a path difference I guess but its not easy for a beginner.
here is my code TRY 1:
public static JsonData LoadFile(string path)
{
var fileContents = File.ReadAllText(path);
var data = JsonMapper.ToObject(fileContents);
return data;
}
public void QuestionLoader()
{
// Load the Json file and store its contents in a 'JsonData' variable
var data = LoadFile(Application.dataPath + "/Resources/json/level1.json");
And Here is my try 2 - Based on Unity Manual - https://docs.unity3d.com/Manual/StreamingAssets.html:
public static JsonData LoadFile(string path)
{
var www = new WWW(path);
return www.text;
//var fileContents = File.ReadAllText(path);
// var data = JsonMapper.ToObject(fileContents);
// return data;
}
public void QuestionLoader()
{
string path = "";
// Load the Json file and store its contents
#if UNITY_ANDROID
path = "jar:file://" + Application.dataPath + "!/assets/Levels/level1.json";
#endif
#if UNITY_EDITOR
path = Application.dataPath + "/StreamingAssets/Levels/level1.json";
#endif
//
var data = LoadFile(path);
If you want to load json that already exist in the project from any platform, you have two options:
1.Put the Json file in the Resources folder then use Resources.Load to read it as a TextAsset. See the end of this answer for example.
2.Make the json file an AssetBundle then use WWW.LoadFromCacheOrDownload to load it.
Any of these should work. Once you read the json file, you can copy it to the Application.persistentDataPath directly so that you will be able to modify it and save it if needed.
I want to store variables in a .txt file - like I always see in peoples config.txt files, where it's like:
var_name = ['"test url"']
I've got the code below that opens the file and reads it (at the moment just debugging and displays what's in the file, at the moment just 1 variable)
System.IO.StreamReader myFile = new System.IO.StreamReader("C:\\conf\\config.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
MessageBox.Show(myString);
What's in the file is
file_name="C:\\test.txt"
Now I'd like to be able to use that variable in my functions in my VB form. How do I go about doing this? And also, how can I do multiple; so I can have basically a big list of vars that the form loads at launch?
So for example:
// Opens file and reads all variables
// Saves all variables to form
// Can now use varaible in form, e.g. messageBox.Show(file_name);
I'm new to C#, I imagine it's similar to an include but the include is local instead of part of the project.
Disclamer: standard practice (i.e. Settings) usually is the best policy, however the question has been asked and can be asnwered:
I suggest using dictionary, e.g.
Dictionary<String, String> MySettings = File
.ReadLines(#"C:\conf\config.txt")
.ToDictionary(line => line.Substring(0, line.IndexOf('=')).Trim(),
line => line.Substring(line.IndexOf('=') + 1).Trim().Trim('"'));
...
String testUrl = MySettings[var_name];
However, if you prefer "variables" you can try ExpandoObject:
dynamic ExpSettings = new ExpandoObject();
var expandoDic = (IDictionary<string, object>) ExpSettings;
foreach (var pair in MySettings)
expandoDic.Add(pair.Key, pair.Value);
...
String testUrl = ExpSettings.var_name;
I store and load data (or variables) with Json Deserialization/ serialization in c#.
Here is Serialiazation: I make an object (postlist which is an object list) that i want to save in a text file That way:
private void save_file()
{
string path = Directory.GetCurrentDirectory() + #"\list.txt";
string json = JsonConvert.SerializeObject(postlist);
File.WriteAllText(path, json);
Application.Exit();
}
You need to install Newtonsoft.Json: http://www.newtonsoft.com/json
.You can do it with the Nuget tool console.
Don"t forget to use:
using Newtonsoft.Json;
Here is a way to get all your data from the text file, this is the deserialization:
private void read_file_list()
{
string line;
try
{
using (StreamReader sr = new StreamReader("list.txt"))
{
line = sr.ReadToEnd();
}
JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;
postlist = JsonConvert.DeserializeObject<List<Post>>(line, jsonSerializerSettings);
}
catch
{
// catch your exception if you want
}
}
And here is how i store all my text in my object list "postlist".
Newtonsoft is very usefull and easy to use, i mostly use it to get data from api's.
This my first answer I hope it will help you.
I have a problem with System.IO.Path.GetFileNameWithoutExtension. If i load a file, the string which is returned by the method contains some hidden chars. In HEX: 3F.
The follwing pictures contains the problem. See the hex editor:
The texfiles were created with Notepad++ and the Encoding is UTF-8 without BOM.
Maybe some one has a solution, thank you!
I created file with Notepad++ v6.6.4 and put the file in debug folder called myFile.txt and the Encoding is "UTF-8 without BOM" and if you apply the next code which read all the text from the original file created above and put all the content in new file in the same directory you will find exactly all the content without any difference.
using System;
using System.IO;
namespace FilePathWithNotepad__
{
class Program
{
static void Main(string[] args)
{
string originalFilePath = Environment.CurrentDirectory + "\\myFile.txt";
string title = Path.GetFileNameWithoutExtension(originalFilePath);
string content = File.ReadAllText(originalFilePath);
string newfile = Path.GetFileName(Environment.CurrentDirectory + "\\new.txt");
File.WriteAllText(newfile,content);
}
}
}
I am trying to get the last modified date from a file, but need its path? Could someone please show me how i can get the file path?
[HttpGet]
public string uploadfile(string token, string filenameP, DateTime modDate, HttpPostedFileBase file)
{
MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
byte[] data = target.ToArray();
//ModDate = File.GetLastWriteTimeUtc("Path");
}
You are creating a new file on the server when you upload. The last modified date will be "now" (the time the file is created). There is no way to snoop the user's machine to get this information (which is not part of the file itself). Can't be done with an HTTP form upload.
Now, some file types may contain metadata in the file which may have pertinent information. If you know the file type and it does contain such metadata then you can open the file and have a look.
You just don't. Most (if not all) browsers do not provide this information for security reasons in internet sceanrios.
You can read date by javascript (HTML5) and send it as hidden input field of form.
Something like
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push(f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() );
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
http://www.html5rocks.com/en/tutorials/file/dndfiles/
In my web application (asp.net,c#) I am uploading video file in a page but I want to upload only flv videos. How can I restrict when I upload other extension videos?
Path.GetExtension
string myFilePath = #"C:\MyFile.txt";
string ext = Path.GetExtension(myFilePath);
// ext would be ".txt"
You may simply read the stream of a file
using (var target = new MemoryStream())
{
postedFile.InputStream.CopyTo(target);
var array = target.ToArray();
}
First 5/6 indexes will tell you the file type. In case of FLV its 70, 76, 86, 1, 5.
private static readonly byte[] FLV = { 70, 76, 86, 1, 5};
bool isAllowed = array.Take(5).SequenceEqual(FLV);
if isAllowed equals true then its FLV.
OR
Read the content of a file
var contentArray = target.GetBuffer();
var content = Encoding.ASCII.GetString(contentArray);
First two/three letters will tell you the file type.
In case of FLV its "FLV......"
content.StartsWith("FLV")
At the server you can check the MIME type, lookup flv mime type here or on google.
You should be checking that the mime type is
video/x-flv
If you were using a FileUpload in C# for instance, you could do
FileUpload.PostedFile.ContentType == "video/x-flv"
I'm not sure if this is what you want but:
Directory.GetFiles(#"c:\mydir", "*.flv");
Or:
Path.GetExtension(#"c:\test.flv")
In addition, if you have a FileInfo fi, you can simply do:
string ext = fi.Extension;
and it'll hold the extension of the file (note: it will include the ., so a result of the above could be: .jpg .txt, and so on....
string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);
The above method works fine with the Firefox and IE: I am able to view all types of files like zip,txt,xls,xlsx,doc,docx,jpg,png.
But when I try to find the extension of file from Google Chrome, I fail.
EndsWith()
Found an alternate solution over at DotNetPerls that I liked better because it doesn't require you to specify a path. Here's an example where I populated an array with the help of a custom method
// This custom method takes a path
// and adds all files and folder names to the 'files' array
string[] files = Utilities.FileList("C:\", "");
// Then for each array item...
foreach (string f in files)
{
// Here is the important line I used to ommit .DLL files:
if (!f.EndsWith(".dll", StringComparison.Ordinal))
// then populated a listBox with the array contents
myListBox.Items.Add(f);
}
It is worth to mention how to remove the extension also in parallel with getting the extension:
var name = Path.GetFileNameWithoutExtension(fileFullName); // Get the name only
var extension = Path.GetExtension(fileFullName); // Get the extension only
You will not be able to restrict the file type that the user uploads at the client side[*]. You'll only be able to do this at the server side. If a user uploads an incorrect file you will only be able to recognise that once the file is uploaded uploaded. There is no reliable and safe way to stop a user uploading whatever file format they want.
[*] yes, you can do all kinds of clever stuff to detect the file extension before starting the upload, but don't rely on it. Someone will get around it and upload whatever they like sooner or later.
You can check .flv signature. You can download specification here:
http://www.adobe.com/devnet/flv/
See "The FLV header" chapter.
private string GetExtension(string attachment_name)
{
var index_point = attachment_name.IndexOf(".") + 1;
return attachment_name.Substring(index_point);
}
This solution also helps in cases of more than one extension like "Avishay.student.DB"
FileInfo FileInf = new FileInfo(filePath);
string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");
Path.GetExtension(file.FileName)) will get you the file name
Im also sharing a test code if someone needs to test and ge the extention or name.
Forming a text file with name test.txt and checking its extention in xUnit.
[Fact]
public void WrongFileExtention_returnError()
{
//Arrange
string expectedExtention = ".csv";
var content = "Country,Quantity\nUnited Kingdom,1";
var fileName = "test.csv";
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(content);
writer.Flush();
stream.Position = 0;
//Act
IFormFile file = new FormFile(stream, 0, stream.Length, "", fileName);
//Assert
Assert.Equal(expectedExtention, Path.GetExtension(file.FileName));
}
Return true as the expected and the filename extention is name.
Hope this helps someone :).
I know this is quite an old question but here's a nice article on getting the file extension as well as a few more values:
Get File Extension in C#
I Hope That Helps :-)!