Click here to Skip to main content
12,075,610 members (66,706 online)
Rate this:
 
Please Sign up or sign in to vote.
I am trying to create a text file, and write some text to it within my Firefox extension in this way:
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 4-Mar-13 1:29am
Daroosh731
Edited 4-Mar-13 1:44am
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Lots of answers from Google[^].
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

This is the right way to do it:
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.
  Permalink  

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web04 | 2.8.160208.1 | Last Updated 6 Mar 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100