Reply to topic

How to save a open file after some changes are made?
Alex D


Joined: 12 Aug 2007
Posts: 1
Reply with quote
The following file is to change the media source of m3u playlists.
I found that I can read the lines of .m3u file, but I cannot save it. How can I save my change?

Code:

================
// Ts script to change the source of the Playlist source

String GetSource()
{
   String strResult;
   Registry.GetString(HKEY_CURRENT_USER,
      "Software\Microsoft\Windows" +
      "CUrrentVersion\Explorer\Shell Folders",
      "Personal", strResult);
   return strResult;
}

String strPath;
strPath = GetSource();

//Ask the uer for an existing m3u file

if (File.BrowseFile(strPath, [Open], "Select a m3u file",
   "m3u Files (*.m3u)|*.m3u"))
{
   File f;

   // Open the selected file

   if (f.Open(strPath))
   {    
      String strLine;
      int count=0;

   while (f.ReadLine(strLine))
   {
      strLine.Replace("F:\Music\",  "E:\Music\");
      count++;
   }
    
   f.Close();

   // Show the results

   Gizmo.WriteDesktop("File $b " +
      File.ParseFile(strPath) +
      " $plain has changed $b " +
      count.ToString());
   }
   else
   {
      Gizmo.WriteDesktop("Error opening file $b " +
         File.ParseFile(strPath));
   }
}
else
{
   Gizmo.WriteDesktop("You selected nothing.");
}
View user's profileSend private message
Logan Mueller
Support

Joined: 16 Nov 2003
Posts: 565
Reply with quote
Hi Alex,

You'll have to open a second file and call WriteLine as you go through each line in the original file. When the loop is finished, replace the original with the second file.

Here are the changes for your code:

[...]

Code:

File f;
File f_temp;

// Copy strPath to strTempPath and change its file extension
// to TMP, for the temporary file

String strTempPath = strPath;
int dot_pos = strTempPath.ReverseFind (".");
if (dot_pos != -1)
{
   strTempPath = strTempPath.Left (dot_pos + 1) + "tmp";
}

// Open the selected file and create a temporary file for the changes

if (f.Open(strPath) && f_temp.Create (strTempPath))
{    
   String strLine;
   int count=0;

   while (f.ReadLine(strLine))
   {
      strLine.Replace("F:\Music\",  "E:\Music\");
      f_temp.WriteLine (strLine);
      count++;
   }
    
   f_temp.Close ();
   f.Close();

   // Replace the original file with the changes

   File.Remove (strPath);
   File.Rename (strTempPath, strPath);


[...]

_________________
Support is provided as a convenience to our users. We make no guarantees in the timeliness and accuracy in our responses. We reserve the right to refuse service to anyone.
View user's profileSend private messageVisit poster's website
How to save a open file after some changes are made?
All times are GMT - 8 Hours  
Page 1 of 1  

  
  

 Reply to topic