Question

How do I programmatically create a text file and write to it in the private:// folder in Drupal 8.8? I found some examples, but all of them use deprecated functions and they don't work.

Here what I have now, but i't s not creating folder and text file in it with content:

use Drupal\Core\StreamWrapper\PrivateStream;
...
...
$output = 'Test Text';
$file_save_path_stream_directory =  'private://gmt';

file_prepare_directory($file_save_path_stream_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);

$fileLocation = $file_save_path_stream_directory . '/test.txt';

$file = file_save_data($output, $fileLocation, FILE_EXISTS_REPLACE);  
Was it helpful?

Solution

If anyone need it, I make it work:

use Drupal\Core\File\FileSystemInterface;

...

  /**
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;


  public function __construct(FileSystemInterface $fileSystem) {
    $this->fileSystem = $fileSystem;
  }

  public function testCreation() {
    $request = 'test content';
    $path = 'private://gmt/';
    if ($this->fileSystem->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY)) {
      /** @var \Drupal\file\FileInterface $file */
      $file = file_save_data(
        $request,
        $path . 'requests.txt'
      );
    }
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top