Notifications
Clear all

[Closed] how to overwrite file ?

I want to let user to save settings in to txt external file, piece of cake:) – till this moment. Now it comes trouble. The real deal is when maxscript try to overwrite file which is already created under current 3ds max session – Runtime error: FileStream cannot create bla bla
( when I create file, restart max I can deleted file only once).
So if I can’t overwrite file maybe I should delete file that can’t be overwrite and save it again.I tried everything to delete this file, close file,gc, delete from dos command,delete filename, nothing works. It seems like file once created have triggered access denied when max is still on duty. Does anyone have any idea what’s the deal with it, how to fix this?
This is code; fire it up once, and txt file will be created, run it again and error will appear.

settingsfile = getSaveFileName types:“Data(.txt)|.csv|All|.|”
try(close settingsfile)catch(); gc()
a_filename=filenameFromPath settingsfile; b_filepath=getFilenamePath settingsfile
todelate=”delete “+(b_filepath+a_filename)
if settingsfile !=undefined then (DOSCommand todelate)
try(deletefile settingsfile)catch(print “error delating file”)
settingsfile_userfile = createfile settingsfile

2 Replies
settingsfile_userfile = createfile settingsfile

This last line creates a new file with same path+name, this new file is still opened.
You have to close it (as you’ve done for first one) before deleting.

working code :

fname = getSaveFileName types:"Data(*.txt)|*.csv|All|*.*|"	-- string
   ff = createFile fname		-- filestream
   close ff					 -- close filestream before deleting
   
   if doesfileexist fname then (	-- if file exists
   	try(deletefile fname)catch(print "error delating file")
   	-- ff should have been deleted and all his data
   )
   
   if NOT doesfileexist fname then (	-- if file does not exist
   	ff2 = createFile fname	-- new filestream based on first file string name
   	close ff2
   	-- ff2 should be on your drive
   )

Hi,

You have not to delete it I think.
You can just overwrite it.

try(close settingsfile)catch()
 if doesFileExists settingsfile then
 (
 	  tfile = openFile settingsfile mode:w 
 			 --overwrite file which is empty now because it's open in write mode
 )else(
 	  tfile = createFile settingsfile 
 )
 format "%
%" 1var 2var to:tfile --if you need something in your file  
 close tfile

I didn’t test it but I think that works.