---
title: "string(withContentsOfFile:)"
framework: foundation
role: symbol
role_heading: Type Method
path: "foundation/nsstring/string(withcontentsoffile:)"
---

# string(withContentsOfFile:)

Returns a string created by reading data from the file named by a given path.

## Declaration

```swift
class func string(withContentsOfFile path: String) -> Any?
```

## Discussion

Discussion If the contents begin with a Unicode byte-order mark (U+FEFF or U+FFFE), interprets the contents as UTF-16 code units. If the contents begin with a UTF-8 byte-order mark (EFBBBF), interprets the contents as UTF-8. Otherwise, interprets the contents as data in the default C string encoding. Since the default C string encoding will vary with the user’s configuration, do not depend on this method unless you are using Unicode or UTF-8 or you can verify the default C string encoding. Returns nil if the file can’t be opened.

## See Also

### Deprecated

- [string(withCString:)](foundation/nsstring/string(withcstring:).md)
- [init(CString:)](foundation/nsstring/init(cstring:)-vkuo.md)
- [string(withCString:length:)](foundation/nsstring/string(withcstring:length:).md)
- [init(CString:length:)](foundation/nsstring/init(cstring:length:)-5ure3.md)
- [init(CStringNoCopy:length:freeWhenDone:)](foundation/nsstring/init(cstringnocopy:length:freewhendone:)-86dm2.md)
- [init(contentsOfFile:)](foundation/nsstring/init(contentsoffile:).md)
- [string(withContentsOf:)](foundation/nsstring/string(withcontentsof:).md)
- [init(contentsOfURL:)](foundation/nsstring/init(contentsofurl:).md)
- [write(toFile:atomically:)](foundation/nsstring/write(tofile:atomically:).md)
- [write(to:atomically:)](foundation/nsstring/write(to:atomically:).md)
- [getCharacters(_:)](foundation/nsstring/getcharacters(_:).md)
- [cString()](foundation/nsstring/cstring().md)
- [lossyCString()](foundation/nsstring/lossycstring().md)
- [cStringLength()](foundation/nsstring/cstringlength().md)
- [getCString(_:)](foundation/nsstring/getcstring(_:).md)
