Click here to Skip to main content
15,921,279 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to create a text file, and write some text to it within my Firefox extension in this way:
JavaScript
try{netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");}
catch (e) {alert("Permission to write file denied."); return 0;}

var file = Components.classes["@mozilla.org/file/local;1"]
           .createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("C:\\BrightCloud_Main\test.txt");
file.create(0x00, 0644);
		
var sFileContent = "This test number 1";
outputStream = Components.classes['@mozilla.org/network/file-outputstream;1']
               .createInstance(Components.interfaces.nsIFileOutputStream);
outputStream.init(file,0x04|0x08|0x20,420,0);
outputStream.write(sFileContent, sFileContent.length);
outputStream.flush();
outputStream.close();

It always fires an exception, displays the message and exits. Any ideas on how to change user privileges to allow to create and edit files?!

Thanks in advance!
Posted
Updated 4-Mar-13 0:44am
v2

Lots of answers from Google[^].
 
Share this answer
 
This is the right way to do it:
JavaScript
var file = Components.classes["@mozilla.org/file/local;1"]
           .createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("C:\\test.txt");		

// WRITE
var text = "Text to be written";
var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
                   .createInstance(Components.interfaces.nsIFileOutputStream);
outputStream.init(file, 0x04 | 0x08 | 0x10, 00002, 0);
outputStream.write(text, text.length);
	
// READ
var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                  .createInstance(Components.interfaces.nsIFileInputStream);
var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
                  .createInstance(Components.interfaces.nsIScriptableInputStream);
inputStream.init(file, 0x04, 00004, 0);
sstream.init(inputStream);
var output = sstream.read(sstream.available());

alert(output);

For a list of all the possible file flags and file permissions that can be used when initializing the Input/Output stream, visit JOSHUA's Article.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900