<!--
{
  "availability" : [
    "iOS: 2.0.0 -",
    "iPadOS: 2.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.0.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSData/write(toFile:options:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSData(im)writeToFile:options:error:"
  },
  "title" : "write(toFile:options:)"
}
-->

# write(toFile:options:)

Writes the data object’s bytes to the file specified by a given path.

```
func write(toFile path: String, options writeOptionsMask: NSData.WritingOptions = []) throws
```

## Parameters

`path`

The location to which to write the receiver’s bytes.

`writeOptionsMask`

A mask that specifies options for writing the data. Constant components are described in [`NSData.WritingOptions`](/documentation/Foundation/NSData/WritingOptions).

## Discussion

This method may not be appropriate when writing to publicly accessible files. To securely write data to a public location, use [`FileHandle`](/documentation/Foundation/FileHandle) instead. For more information, see [Securing File Operations](https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW9) in [Secure Coding Guide](https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Introduction.html#//apple_ref/doc/uid/TP40002415).

> Handling Errors in Swift:
> In Swift, this method returns `Void` and is marked with the `throws` keyword to indicate that it throws an error in cases of failure.
> 
> You call this method in a `try` expression and handle any errors in the `catch` clauses of a `do` statement, as described in [Error Handling](https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html) in [The Swift Programming Language](https://docs.swift.org/swift-book/) and `About Imported Cocoa Error Parameters`.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)