Tag Archive for file

Ruby script to save a string to a file.

# Save a string to a file.
myStr = "This is a test"
aFile = File.new("myString.txt", "w")
aFile.write(myStr)
aFile.close

source

Force File Download version 2.0 with configurable transfer rates

<?php

/**
 * This is the Force File Download class of the Skyward Portal
 * @package Skyward_Landing_Page
 * @subpackage Force File Download
 * @filesource
 * @author Matt Ford
 * @version 1.0
 */
 
class com_forcedownload {
	
	/**
	 * This method executes necessary methods based on request data
	 * @access public
	 * @author Matt Ford
	 * @param array $data configuration and request information
	 */
	public function preProcess($data) {
		$data->request["file"] = str_replace(" ", "+", $data->request["file"]);
		
		switch ($data->request["task"]) {
			case "forcefeed":
			default:
				$this->forceFeed($data);
				break;
		}
	}
	
	/**
	 * This method determines if the file path is good and executes the necessary method
	 * @access private
	 * @author Matt Ford
	 * @param array $data configuration and request information
	 */
	private function forceFeed ($data) {
		global $controller, $controller_config;
		
		$file = $controller_config->downloadRootDir . $controller->decrypt($data->request["file"]);

		if (file_exists($file) === true && is_file($file) === true && is_readable($file) === true) {
			$this->performDownload($file);
		}
		else {
			$this->invalidFile($file);
		}
	}
	
	/**
	 * This method performs the necessary actions to force the users browser to prompt a download box
	 * @access private
	 * @author Matt Ford
	 * @param string $file path to file
	 */
	private function performDownload($file) {
		$download_rate = 10000; //kbps
		$extension = strtolower(substr(strrchr($file, "."), 1));
		
		switch ($extension) {
			
			case "doc":
			case "docx":
				$mime = "application/msword";
				break;
				
			case "exe":
				$mime = "application/octet-stream";
				break;
				
			case "gif":
				$mime = "image/gif";
				break;
				
			case "jpg":
			case "jpeg":
				$mime = "image/jpeg";
				break;
				
			case "txt":
				$mime = "text/plain";
				break;
				
			case "xls":
			case "xlsx":
				$mime = "application/excel";
				break;
				
			default:
				$mime = "application/octet-stream";
				break;
		}
		
		header ("Content-Description: File Transfer");
		header ("Content-Disposition: attachment; filename="" . str_replace(" ", "_", basename($file)) . "";");
		header ("Content-Type: " . $mime);
		header ("Content-Transfer-Encoding: binary");
		header ("Content-Length: " . filesize($file));

		flush();
		ob_flush();
		
		$fp = fopen($file, "r");
		
		while(!feof($fp)) {
			print fread($fp, round($download_rate * 1024));
			flush();
			ob_flush();
			sleep(1);
		}
		
		fclose($fp);
		die();
	}
	
	/**
	 * This method simply echoes an error message of a bad file/path
	 * @access private
	 * @author Matt Ford
	 * @param string $file path to file
	 */
	private function invalidFile($file) {
		global $controller_config;
		//echo """ . basename($file) . "" is either not a valid file or not in the specified path";
		//die();
		
		$this->performDownload($controller_config->path . "/supplementalFiles/img/404_File_Not_Found.jpg");
	}
}
?>

source

Copy a file

Dim fso, newFile, tplFile, fPath

fPath = "C:"
tplFile = fPath & "tpl.txt"
newFile = fPath & "export.txt"

Set fso = CreateObject("Scripting.FileSystemObject")

if fso.FileExists(newFile) then
	MsgBox "File already exists."
else
	fso.CopyFile tplFile, newFile
	MsgBox "File copied."
end if

source

Persisting data using XML config files in WinForms (saving and restoring user and application data)

Exported file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <HawkConfigGUI.Properties.Settings>
            <setting name="FpgaFilePath" serializeAs="String">
                <value>testfpga</value>
            </setting>
            <setting name="FirmwareFilePath" serializeAs="String">
                <value>test</value>
            </setting>
        </HawkConfigGUI.Properties.Settings>
    </userSettings>
</configuration>

Class:
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

public static class SettingsIO
{
    internal static void Import(string settingsFilePath)
    {
        if (!File.Exists(settingsFilePath))
        {
            throw new FileNotFoundException();
        }

        var appSettings = Properties.Settings.Default;
        try
        {
            var config = 
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);

            string appSettingsXmlName = 
Properties.Settings.Default.Context["GroupName"].ToString(); 
// returns "MyApplication.Properties.Settings";

            // Open settings file as XML
            var import = XDocument.Load(settingsFilePath);
            // Get the whole XML inside the settings node
            var settings = import.XPathSelectElements("//" + appSettingsXmlName);

            config.GetSectionGroup("userSettings")
                .Sections[appSettingsXmlName]
                .SectionInformation
                .SetRawXml(settings.Single().ToString());
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("userSettings");

            appSettings.Reload();
        }
        catch (Exception) // Should make this more specific
        {
            // Could not import settings.
            appSettings.Reload(); // from last set saved, not defaults
        }
    }

    internal static void Export(string settingsFilePath)
    {
        Properties.Settings.Default.Save();
        var config = 
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);
        config.SaveAs(settingsFilePath);
    }
}

source

WordPress – Get template file used

get_post_meta($post->ID,'_wp_page_template',true)

source

Directory Class Methods

puts File.dirname(__FILE__)

#Keeps track of where you are at this moment, it might change often
puts Dir.pwd
#Change Directory
#puts Dir.chdir( File.join('', '') )
#An array of info within the directories
puts Dir.entries('.')
#Code block of files within a directory
Dir.entries('.').each do |entry|
  print entry + ": "
  if File.file?(entry) && File.readable?(entry)
    File.open(entry, 'r') do |file|
      puts file.gets
    end
  else
    puts
  end
end

Dir.foreach("."){ |entry| puts entry }

Dir.mkdir('temp_directory')
Dir.delete('temp_directory')

source

Get file extension

function getExtension($filename)
{
    return ('.' . ($ext = pathinfo($filename, PATHINFO_EXTENSION)) == $filename) ? null : $ext;
}

// Example:
var_dump(getExtension('.htaccess'), getExtension('image.jpg'));
// Result:
// NULL
// string(3) "jpg"

source

Reading from Files + File Class Methods

=begin
'r' = Read from start (it must exist beforehand)
'w' = Start a new file, Write from the start but destroys any existing data (very distructive) 
'a' = Append / Write from end
'r+' = Read and write without being destructive


#File.new( 'file_name.extension', 'r|w|a|r+|w+|a+' )
file = File.new( 'file_example.txt', 'w' )

#You must close to free up the resources
file.close

#Open a file, pass a block of instructions, and it will open and close on its own
File.open( 'file_example.txt', 'r') do |file|
  #Read data from the file
end

=end

file = File.new("file_example.txt", "w")
#Various ways to print to a file
file.puts "Ruby"
file.print "programing
"
file.write "is"
file << "fun"
#Close method is required to actually save 
file.close

File.open("file_example.txt", "r") do |file|
  #While there is a new line
  while line = file.gets
    puts "** " + line.chomp.reverse + " **"
  end
end

File.open("file_example.txt", "r") do |file|
  file.each_line { |line| puts line.upcase }
end


### More File class methods ###

file = "file_example.txt"

#See if this file exists
puts File.exist?(file)
#Is this a file? 
puts File.file?(file)
#IS this a directory?
puts File.directory?(file)
#Readable?
puts File.readable?(file)
#Writable?
puts File.writable?(file)
#Executable?
puts File.executable?(file)
#File Size?
puts File.size(file)
#Just get me what's in the ned
full_path =  File.expand_path(file) 
puts File.basename(full_path)
#Find the extension
puts File.extname(file)
#Last time it was accessed
puts File.atime(file)
#Last modified time
puts File.mtime(file)
#Last status change time.  Read/Write/Owner/Group/or Permissions
puts File.ctime(file)

source

PHP force file download instead opening in new tab/window

$file_name = $_GET['file'];
 
// make sure it's a file before doing anything!
if(is_file($file_name))
{
 
    /*
        Do any processing you'd like here:
        1.  Increment a counter
        2.  Do something with the DB
        3.  Check user permissions
        4.  Anything you want!
    */
 
    // required for IE
    if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
 
    // get the file mime type using the file extension
    switch(strtolower(substr(strrchr($file_name,'.'),1)))
    {
        case 'pdf': $mime = 'application/pdf'; break;
        case 'zip': $mime = 'application/zip'; break;
        case 'jpeg':
        case 'jpg': $mime = 'image/jpg'; break;
        default: $mime = 'application/force-download';
    }
    header('Pragma: public');   // required
    header('Expires: 0');       // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private',false);
    header('Content-Type: '.$mime);
    header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: '.filesize($file_name));    // provide file size
    readfile($file_name);       // push it out
    exit();
 
}

source

Get filename from full url

private static function getFilenameFromUrl(url:String):String
{
	var letters:Array= [];
	var charPosition:int= url.length;
	var currentCharacter:String;

	while(currentCharacter != '/' && currentCharacter != '') {
		currentCharacter = url.charAt(charPosition);
		letters.push( currentCharacter);
		charPosition--;
	}
	letters = letters.reverse();
	letters.shift();
	var filename:String = letters.join('');
	return filename;
}

source